MEF用4.5打开泛型问题

时间:2012-08-20 08:56:34

标签: .net mef .net-4.5

我们正在使用这样的MEF Contrib开放式仿制药支持:

[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>>();
    }
}

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

似乎必须在TestClass2上使用显式[Export(typeof(ITest2&lt;&gt;))]属性,或更改定义:

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

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

我原以为开放通用接口上[InheritedExport]的默认行为与[InheritedExport(typeof(ITest2&lt;&gt;))]相同。

谢谢, 史蒂夫

2 个答案:

答案 0 :(得分:5)

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

有几种解决方法,没有一种是理想的。

  1. 使界面成为抽象基类
  2. 从界面中删除InheritedExport,并使用“导出属性”显式标记派生类。
  3. 我希望这会有所帮助。

答案 1 :(得分:-1)

当使用.NET 4.5实现的开放式泛型以及InheritedExport时,这看起来像一个错误。 MEF团队正在调查。

您声称通过在[InheritedExport(typeof(ITest2<>))]上添加ITest2<T>为您解决了问题,但是在我尝试重复此操作时,这也无效。我只是通过在Export(typeof(ITest2<>))上直接添加显式Test2Class来实现它。

您能否提供一些有关您收到的错误的详细信息?你还在使用MEF贡献的东西还是你在这个项目中停止使用它?