gpt4 book ai didi

c# - 你如何使用 ExportFactory

转载 作者:行者123 更新时间:2023-11-30 13:48:46 25 4
gpt4 key购买 nike

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

1) No valid exports were found that match the constraint '((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"))))', invalid exports may have been rejected.

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

最佳答案

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

您可能想要导入多个工厂,包括像这样的元数据:

[ImportMany]
private IEnumerable<ExportFactory<IFoo,IFooMeta>> 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;
}
}

关于c# - 你如何使用 ExportFactory<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11488297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com