即使程序集仅加载一次,相同类型的转换也会失败

时间:2018-08-07 08:44:02

标签: c# .net .net-core mef

我有一个下面的.NET Core 2.0应用程序的最小示例,该应用程序使用MEF作为其DI容器,并用目录中的所有程序集填充它:

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var files = Directory.EnumerateFiles(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "*.dll");
            var catalogs = files.Select(path => new AssemblyCatalog(Assembly.LoadFile(path)));

            var container = new CompositionContainer(new AggregateCatalog(catalogs));

            var foo = container.GetExportedValue<IFoo>();
            foo.DoSomething();
        }
    }

    public interface IFoo
    {
        void DoSomething();
    }

    [Export(typeof(IFoo))]
    public class Foo : IFoo
    {
        public void DoSomething()
        {
            Console.WriteLine("42");
        }
    }
}

在.NET Core 2.0中运行这段代码会遇到System.ComponentModel.Composition.CompositionContractMismatchException: 'Cannot cast the underlying exported value of type 'Test.Foo (ContractName="Test.IFoo")' to type 'Test.IFoo'.'。其根源似乎是实际失败的演员表。

但是,当我在Visual Studio中打开模块视图时,它告诉我我的应用程序仅加载一次。因此,据我所知,这种异常不应发生,但显然是可以的。有人解释为什么吗?

注意:可以通过过滤files中的当前程序集并手动为当前程序集添加程序集目录来避免该异常。我知道这一点,但首先我不理解该异常。

0 个答案:

没有答案