MEF用4.5打开泛型问题

Ste*_*rew 1 .net mef .net-4.5

我们正在使用这样的MEF Contrib open generics支持:

[InheritedExport]
interface ITest2<T>
{
    void Execute();
}

class TestClass2<T> : ITest2<T>
{
    public void Execute()
    {
        Console.WriteLine();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var catalog = new AssemblyCatalog(typeof(Program).Assembly);
        var container = new CompositionContainer(catalog);
        var test2 = container.GetExportedValues<ITest2<string>>();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,自从安装.NET Framework 4.5以来,此代码不再有效.在构建.NET 4.5或.NET 4.0之后,它不仅不再起作用,而且还破坏了现有的编译应用程序.

似乎必须在TestClass2上使用显式[Export(typeof(ITest2 <>))]属性,或者更改定义:

[InheritedExport(typeof(ITest2<>))]
interface ITest2<T>
{
    void Execute();
}
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么这会改变?奇怪的是,MEF的开放式泛型支持(在4.5中)也失败了,在开放的通用接口上有一个非类型的[InheritedExport]属性.

我原以为开放通用接口上[InheritedExport]的默认行为与[InheritedExport(typeof(ITest2 <>))]相同.

谢谢,史蒂夫

小智 5

这是Open Generics支持的.Net 4.5 MEF实现中的一个错误.它将在.Net框架的下一个版本中修复.

有几种解决方法,它们都不是理想的.

  1. 使接口成为抽象基类
  2. 从接口中删除InheritedExport,并使用"导出属性"显式标记派生类.

我希望这有帮助.