简体   繁体   English

MEF通用进口

[英]MEF Generic Imports

I have the following example code using 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
}

This doesn't seem to work - the foo field is null . 这似乎不起作用 - foo字段为null Is this because its type isn't seen by MEF as IFoo<String> ? 这是因为它的类型不被MEF看作IFoo<String>吗?

foo is null because you are creating the instance yourself. foo为null,因为您自己正在创建实例。 You need to have the container create the instance. 您需要让容器创建实例。

Additionally, you will want to check out the GenericCatalog if you plan on working importing/exporting generics. 此外,如果您计划使用导入/导出泛型,则需要查看GenericCatalog

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM