首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在mef2中模拟继承端口特性

如何在mef2中模拟继承端口特性
EN

Stack Overflow用户
提问于 2015-12-02 01:11:58
回答 1查看 250关注 0票数 0

我正在使用MEF2,并阅读了一些关于mef1和mef2的教程。

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

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

这是我的代码片段:

代码语言:javascript
复制
var convention = new ConventionBuilder();
convention.ForTypesDerivedFrom<IMainTabsControl>().Export<IMainTabsControl>();
convention.ForTypesDerivedFrom<IShell>().Export<IShell>().Shared();
// here is where i am struggeling.
convention.ForTypesMatching(type => typeof (ICrawlerKeyProvider).IsAssignableFrom(type)).Export(builder => builder.AsContractType(typeof(bool)));

var configuration = new ContainerConfiguration();
MefContainer = configuration.WithAssemblies(new []{ Assembly.GetExecutingAssembly(),  }, convention).CreateContainer();

所以有三种选择

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

据我所知,很容易做到:

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

但是使用ForTypesMatching,我似乎不能做我想做的事情,因为构建器变量没有可用的类型信息。

,我是不是想做一些奇怪的事情,在mf2中是不可能的,但在mf1?中却是可能的。

更新:

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

EN

回答 1

Stack Overflow用户

发布于 2015-12-02 02:19:55

属性:

代码语言:javascript
复制
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;
    }
}

公约守则:

代码语言:javascript
复制
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));
            }
        }
    }
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34033240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档