我想导出Foo
具有多个元数据选项的类型:
public interface IFoo
{
void Do ();
}
[ExportFoo ("Bar", "1.0")]
[ExportFoo ("Baz", "1.0")]
[ExportFoo ("Baz", "2.0")]
public class Foo : IFoo
{
public void Do () {}
}
我已经这样声明ExportFooAttribute
了:
public interface IFooMeta
{
string Name { get; }
string Version { get; }
}
[MetadataAttribute, AttributeUsage (AttributeTargets.Class, AllowMultiple = true)]
public class ExportFooAttribute : ExportAttribute, IFooMeta
{
public string Name { get; private set; }
public string Version { get; private set; }
public ExportFooAttribute (string name, string version) : base(typeof(IFoo))
{
Name = name;
Version = version;
}
}
根据文档,当AllowMultiple
设置为时true
,元数据实际上包含原始元数据的属性数组,所以我以这种方式导入类型:
public interface IFooMultiMeta
{
string[] Name { get; }
string[] Version { get; }
}
public class Program
{
[ImportMany]
public List<Lazy<IFoo, IFooMultiMeta>> Foos { get; set; }
private static void Main ()
{
new Program().MainInternal();
}
private void MainInternal ()
{
new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly())).ComposeParts(this);
foreach (Lazy<IFoo, IFooMultiMeta> lazyFoo in Foos)
for (int i = 0; i < lazyFoo.Metadata.Name.Length; i++)
Console.WriteLine("* {0} {1}", lazyFoo.Metadata.Name[i], lazyFoo.Metadata.Version[i]);
Console.WriteLine(Equals(Foos[0].Metadata, Foos[1].Metadata));
Console.ReadKey();
}
}
我希望得到一个Foo
带有元数据的实例,其中包含 3 个值的数组。但是,我得到了这个:
* Baz 2.0
* Baz 1.0
* Bar 1.0
* Baz 2.0
* Baz 1.0
* Bar 1.0
* Baz 2.0
* Baz 1.0
* Bar 1.0
False
更糟糕的是,元数据实例不同,所以我什至无法正确过滤掉重复项。
问题:如何正确导出一个类以满足元数据属性的多种组合?
完整示例: http: //pastebin.com/WyjN95gr