开发者

MEF Generic Imports

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 = 开发者_JAVA百科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> ?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜