【问题标题】:How to know the original type of a class Exported as an interface in MEF如何知道在MEF中导出为接口的类的原始类型
【发布时间】:2014-06-23 05:32:05
【问题描述】:

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

例如,我要获取MailViewModel的类型:

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

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

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

当我使用 [Export] 以原始类型导出我的班级时,我可以写这个来了解特定属性是否装饰了我的班级:

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

知道导出的类型和合同名称(IPlugin 和“Mail”),我如何知道导出的类是否使用特定属性进行装饰(无需实例化)。

【问题讨论】:

    标签: c# mef


    【解决方案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);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-18
      • 2020-01-13
      • 2014-12-29
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      相关资源
      最近更新 更多