MEF通用import
我有以下使用MEF的示例代码:
public interface IFoo {} public class Foo : IFoo {} [Export(typeof(IFoo))] public class Foo : Foo {} public class Bar { [Import] private readonly IFoo 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(); //bar.foo would be null }
这似乎不起作用 – foo
字段为null
。 这是因为它的类型不被MEF看作IFoo
吗?
foo为null,因为您自己创建实例。 您需要让容器创建实例。
此外,如果您计划使用导入/导出generics,则需要查看GenericCatalog 。