0

我正在使用 MEF2 并阅读了一些关于 MEF 1 和 MEF 2 的教程。

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

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

这是我的代码片段:

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();

所以真的有3个选项:

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

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

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

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

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

更新:

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

4

1 回答 1

-1

属性:

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));
            }
        }
    }
}
于 2015-12-02T02:19:55.130 回答