我是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()
{
}
}
Run Code Online (Sandbox Code Playgroud)
问题似乎是您希望导入单个ExportFactory<IFoo>,但您已导出两个不同的IFoo实现.在您的示例中,MEF无法在两个实现之间做出决定.
您可能想要导入多个工厂,包括如下元数据:
[ImportMany]
private IEnumerable<ExportFactory<IFoo,IFooMeta>> FooFactories
{
get;
set;
}
Run Code Online (Sandbox Code Playgroud)
IFooMeta将在哪里声明如下:
public interface IFooMeta
{
string CompType { get; }
}
Run Code Online (Sandbox Code Playgroud)
然后你可以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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7211 次 |
| 最近记录: |