你如何使用ExportFactory

我是MEF的新手,正在尝试使用ExportFactory。 我可以使用ExportFactory根据用户插入对象创建列表吗? 样本将类似于下面显示的内容。 我可能不理解ExportFactory的使用,因为在运行时我在组合期间得到如下所示的错误。

1)没有找到与约束’((exportDefinition.ContractName ==“System.ComponentModel.Composition.ExportFactory(CommonLibrary.IFoo)”)AndAlso(exportDefinition.Metadata.ContainsKey(“ExportTypeIdentity”)AndAlso“System”匹配的有效导出)。 ComponentModel.Composition.ExportFactory(CommonLibrary.IFoo)“。Equals(exportDefinition.Metadata.get_Item(”ExportTypeIdentity“))))’,无效导出可能已被拒绝。

class Program { static void Main(string[] args) { Test mytest = new Test(); } } public class Test : IPartImportsSatisfiedNotification { [Import] private ExportFactory FooFactory { get; set; } public Test() { CompositionInitializer.SatisfyImports(this); CreateComponent("Amp"); CreateComponent("Passive"); } public void OnImportsSatisfied() { int i = 0; } public void CreateComponent(string name) { var componentExport = FooFactory.CreateExport(); var comp = componentExport.Value; } } public interface IFoo { double Name { get; set; } } [ExportMetadata("CompType", "Foo1")] [Export(typeof(IFoo))] [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)] public class Foo1 : IFoo { public double Name { get; set; } public Foo1() { } } [ExportMetadata("CompType", "Foo2")] [Export(typeof(IFoo))] [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)] public class Foo2 : IFoo { public double Name { get; set; } public Foo2() { } } 

问题似乎是您希望导入单个ExportFactory ,但您已导出两个不同的IFoo实现。 在您的示例中,MEF无法在两个实现之间做出决定。

您可能想要导入多个工厂,包括如下元数据:

 [ImportMany] private IEnumerable> FooFactories { get; set; } 

其中IFooMeta将被声明为:

 public interface IFooMeta { string CompType { get; } } 

然后你可以像这样实现CreateComponent

 public IFoo CreateComponent(string name, string compType) { var matchingFactory = FooFactories.FirstOrDefault( x => x.Metadata.CompType == compType); if (matchingFactory == null) { throw new ArgumentException( string.Format("'{0}' is not a known compType", compType), "compType"); } else { IFoo foo = matchingFactory.CreateExport().Value; foo.Name = name; return foo; } }