MEF通用进口

Lee*_*son 4 c# generics mef

我有以下使用MEF的示例代码:

public interface IFoo<T> 
{}

public class Foo<T> : IFoo<T> 
{}

[Export(typeof(IFoo<String>))]
public class Foo : Foo<String> 
{}

public class Bar<T>
{
   [Import]
   private readonly IFoo<T> foo;
}

static void Main()
{
   var catalog = new AggregateCatalog();
   catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
   var container = new CompositionContainer(catalog);
   container.ComposeParts();

   var bar = new Bar<String>();
   //bar.foo would be null
}
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用 - foo领域是null.这是因为MEF看不到它的类型IFoo<String>吗?

Tom*_*ers 8

foo为null,因为您自己正在创建实例.您需要让容器创建实例.

此外,如果您计划使用导入/导出泛型,则需要查看GenericCatalog.