我怎样才能模仿mef2中的inheritedexport功能

时间:2015-12-02 01:11:59

标签: mef2

我正在使用MEF2并阅读MEF 1和MEF 2上的几个教程。

到目前为止,我发现的最好的是这一个:http://www.codeproject.com/Articles/366583/MEF-Preview-Beginners-Guide

虽然我确实让导出工作得很好,我真的想用属性样式来做,因为在接口上使用InheritedExport似乎比在我声明的接口和我的容器之间来回更方便约定。

这是我的代码片段:

library("party")
air.ct <- ctree(Ozone ~ ., data = airq)
par(bg = "grey")
plot(air.ct, inner_panel=node_inner(air.ct, pval = TRUE, id = FALSE),
  terminal_panel = node_boxplot(air.ct, id = FALSE))

所以真的有3个选项:

  • 我在MEF 2中找不到重命名的功能
  • 我没有使用正确的方法
  • 我错过了一些明显的东西

据我所知,它应该很容易:

  • 检查(自定义)属性的类型
  • 为包含所需属性的类型提取所需的导出类型
  • 完成导出

但是使用ForTypesMatching,我似乎无法做我想要的,因为没有可用于构建器变量的类型信息。

我是否尝试做一些奇怪的事情,这在MEF 2中是不可能的,但在MEF 1中是可能的?

更新

有趣的阅读:http://blog.slaks.net/2014-11-16/mef2-roslyn-visual-studio-compatibility/

1 个答案:

答案 0 :(得分:0)

属性:

public class ExportAsAttribute : Attribute
{
    public Type ContractType { get; set; }

    public string ContactName { get; set; }

    public ExportAsAttribute(Type contractType)
    {
        ContractType = contractType;
    }

    public ExportAsAttribute(Type contractType, string contactName)
    {
        ContactName = contactName;
        ContractType = contractType;
    }
}

公约代码:

        var allTypes = GetAllAssemblies().SelectMany(d => d.ExportedTypes);
        foreach (var type in allTypes)
        {
            var attr = type.GetCustomAttribute<ExportAsAttribute>(true);
            if (attr != null)
            {
                foreach (var derivedType in allTypes.Where(d => !d.IsAbstract && !d.IsInterface && type.IsAssignableFrom(d)))
                {
                    if (string.IsNullOrEmpty(attr.ContactName))
                    {
                        convention.ForType(derivedType).Export(config => config.AsContractType(attr.ContractType));
                    }
                    else
                    {
                        convention.ForType(derivedType).Export(config => config.AsContractType(attr.ContractType).AsContractName(attr.ContactName));
                    }
                }
            }
        }
相关问题