简体   繁体   English

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

[英]How to know the original type of a class Exported as an interface in MEF

Is it possible to get the type of a class exported as an interface via mef using a contract name. 是否可以使用协定名称通过mef导出为接口导出的类的类型。

exemple, I want to get the type MailViewModel: 例如,我要获取MailViewModel类型:

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

with MEF I can get a Lazy for the contract name "Mail" but I don't know how to get the type MailViewModel. 使用MEF,我可以为合同名称“ Mail”获得一个懒惰,但我不知道如何获取MailViewModel类型。

I need to know this type because I "can" have on the class exported as IPlugin a specific attribute. 我需要知道这种类型,因为我可以在作为IPlugin导出的类上具有特定属性。 Depending on this attribute I will allow or not to create the value of this plugin (in a navigation scenario). 根据此属性,我将允许或不允许创建此插件的值(在导航方案中)。

when I export my class under their original type with [Export] I can write this to know if the specific attribute decorate my class : 当我使用[Export]以其原始类型导出类时,可以编写此代码以了解特定属性是否装饰了我的类:

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

Knowing the type of the export and the contractname (IPlugin and "Mail"), how can I know if the exported class is or isn't decorate with a specific attribute (without instantiate it). 了解导出的类型和合同名称(IPlugin和“邮件”)后,如何知道导出的类是否使用特定属性进行修饰(不实例化)。

this will give you all the types that have an export of a certain type and contract name. 这将为您提供具有特定类型和合同名称的出口的所有类型。 This is my take on this blog http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/ 这是我对这个博客的看法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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM