MEF Generic Imports

感情迁移 提交于 2019-12-07 08:45:41

问题


I have the following example code using 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. Is this because its type isn't seen by MEF as IFoo<String> ?


回答1:


foo is null because you are creating the instance yourself. 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.



来源:https://stackoverflow.com/questions/5091183/mef-generic-imports

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!