如何知道在MEF中导出为接口的类的原始类型

时间:2014-05-06 14:25:07

标签: c# mef

是否可以使用合约名称通过mef获取作为接口导出的类的类型。

例如,我想获得MailViewModel类型:

[Export(typeof(IPlugin), "Mail")
public class MailViewModel: IPlugin { }

使用MEF我可以获得Lazy的合同名称“Mail”,但我不知道如何获得MailViewModel类型。

我需要知道这种类型,因为我“可以”在作为IPlugin导出的类中具有特定属性。根据此属性,我将允许或不创建此插件的值(在导航方案中)。

当我使用[Export]导出我的类在其原始类型下时,我可以写这个来知道特定属性是否装饰我的类:

Attribute.GetCustomAttributes(typeof(myviewmodel), typeof(myattribute));

知道导出的类型和合同名称(IPlugin和“Mail”),我怎么知道导出的类是否装饰了特定属性(没有实例化)。

1 个答案:

答案 0 :(得分:1)

这将为您提供具有某种类型和合同名称导出的所有类型。这是我对此博客的看法http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/

    private static IEnumerable<Type> GetExportTypes(ComposablePartCatalog catalog, Type type, string contractName)
    {
        return catalog.Parts.Where(
            part =>
            part.ExportDefinitions.Any(
                e =>
                e.ContractName == contractName && e.Metadata.ContainsKey("ExportTypeIdentity") &&
                e.Metadata["ExportTypeIdentity"].Equals(
                    type.FullName))).Select(part => ReflectionModelServices.GetPartType(part).Value);
    }