C# 在MEF中不使用ImportAttribute或ImportManyaAttribute获取导出的元数据?
我认为C# 在MEF中不使用ImportAttribute或ImportManyaAttribute获取导出的元数据?,c#,prism,mef,C#,Prism,Mef,我认为ImportAttribute或ImportManyAttribute幕后应该使用MEF的一些核心方法来获得导出的元数据与导出类型的实际实例配对。使用这些属性可以在以下设置中正常工作: //the metadata interface public interface IMetadata { string Name {get;} } //the custom ExportAttribute [AttributeUsage(AttributeTargets.Class, AllowM
ImportAttribute
或ImportManyAttribute
幕后应该使用MEF的一些核心方法来获得导出的元数据与导出类型的实际实例配对。使用这些属性可以在以下设置中正常工作:
//the metadata interface
public interface IMetadata {
string Name {get;}
}
//the custom ExportAttribute
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
[MetadataAttribute]
public class CustomExportAttribute : ExportAttribute, IMetadata {
public string Name {get;set;}
}
//the class which need to be exported (both value and metadata)
[CustomExport(Name = "someName")]
public class A {
}
//the class which imports the exported value and metadata
[Export]
public class B {
[Import]
public Lazy<A, IMetadata> AData {get;set;}
}
但是,我不想使用类B
,在这种情况下,如何获得A的导出实例对及其元数据?由于不使用任何类(如B
),因此在这种情况下也不使用属性ImportAttribute
。
以下是我尝试过的:
var ac = new AggregateCatalog();
ac.Catalogs.Add(new DirectoryCatalog("."));
var c = new CompositionContainer(ac);
var a = c.GetExportedValue<Lazy<A,IMetadata>>();
var ac=new AggregateCatalog();
ac.Catalogs.Add(新目录(“.”);
var c=新合成容器(ac);
var a=c.GetExportedValue();
上面的最后一行抛出异常importCardinalismatchException,如下所示:
var ac = new AggregateCatalog();
ac.Catalogs.Add(new DirectoryCatalog("."));
var c = new CompositionContainer(ac);
var b = c.GetExportedValue<B>();
var data = b.AData.Value;//some instance of A here
var mdata = b.AData.Metadata;//some metadata of A here
未找到与约束匹配的导出:ContractName System.Lazy(Test.A,Test.IMetadata)RequiredTypeIdentity System.Lazy(Test.A,Test.IMetadata)
我相信一定有某种方法可以直接获取导出值(类型实例及其元数据对),而不必使用虚拟类,ImportAttribute
用于将导出值存储在该类的某些属性中
我还在开始学习MEF和Prism。确实有办法!不需要在其他类中导入导出。只需使用GetExport
var wow = c.GetExport<A, IMetadata>();
var wow=c.GetExport();
这将返回您想要的,一个惰性希望这有帮助 嗯,它有点隐蔽,真的很有帮助,谢谢。我关心的问题已经很久了,因为我现在涉及到其他问题,我还没有测试过这个,但我相信它应该会起作用!