MEF通用进口 [英] MEF Generic Imports

查看:168
本文介绍了MEF通用进口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MEF下面的示例代码:

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
}

这不似乎工作 - 字段是。难道这是因为它的类型不是由MEF视为的IFoo<弦乐>

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是空。你需要有容器创建实例。

foo is null because you are creating the instance yourself. You need to have the container create the instance.

此外,你将要签出的 GenericCatalog 如果你打算在工作导入/导出仿制药

Additionally, you will want to check out the GenericCatalog if you plan on working importing/exporting generics.

这篇关于MEF通用进口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆