我是 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<IFoo> 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()
{
}
}