在 MEF 中不使用 ImportAttribute 或 ImportManyAttribute 获取导出的元数据?

Get exported metadata without using ImportAttribute or ImportManyAttribute in MEF?

我相信幕后的 ImportAttributeImportManyAttribute 应该使用 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 的导出值时,我可以通过 IMetadata 界面浏览带有 A 及其关联元数据的正确导出实例的 AData,如下所示:

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

但是我不想在这种情况下使用class B,我怎样才能获得导出的A实例及其元数据对?因为没有使用任何 class(如 B),所以在这种情况下也没有使用属性 ImportAttribute。 这是我尝试过的:

var ac = new AggregateCatalog();
ac.Catalogs.Add(new DirectoryCatalog("."));
var c = new CompositionContainer(ac);
var a = c.GetExportedValue<Lazy<A,IMetadata>>();

上面最后一行抛出异常ImportCardinalityMismatchException,像这样:

No exports were found that match the constraint: ContractName System.Lazy(Test.A,Test.IMetadata) RequiredTypeIdentity System.Lazy(Test.A,Test.IMetadata)

我相信一定有某种方法可以直接获取导出值(类型实例及其元数据对),而无需使用虚拟 class,其中 ImportAttribute 用于存储class.

中的某些 属性 中的导出值

我仍在开始使用 MEF 和 Prism。

确实有办法!无需在另一个 class 中导入导出。只需使用 GetExport< T, TMetadataView > 方法。根据您的代码,我仅通过添加使其工作:

var wow = c.GetExport<A, IMetadata>();

这个returns正是你想要的,一个Lazy < T, TMetadataView >

希望对您有所帮助!