在 C# 中使用 MEF 时如何为导出属性创建包装器?

How can I create a wrapper for the Export attribute when using MEF with C#?

我有一个使用 Managed Extensibility Framework (MEF) 和 ASP.NET MVC 5 的应用程序。这种架构允许我有一个可插入的设计,我可以在其中构建多个应用程序和 运行 所有这些到一个主应用程序中。它还让我可以在一个中心位置进行身份验证和许可 validation/loading。

要使 MVC 5 与 MEF 一起工作,每个控制器都必须具有唯一的导出值。因此,我必须将这两行代码添加到我的每个控制器

[Export("SomeUniqueValue1", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]

为了使每个插件的导出值都是唯一的,我喜欢将插件名称连接到导出值。所以我不使用上面的两行,而是使用类似的东西

[Export("PluginName.SomeUniqueValue1", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]

现在,我希望通过删除上面的 2 行代码来节省一些编码时间,所以一个喜欢。我希望像下面这样的行

[MefExport("SomeUniqueValue1")]

然后 MefExport class 将处理插件名称与提供的名称的连接,并以某种方式调用 Export class 和 PartCreationPolicy

我如何创建一个 class "i.e. MefExport" 扩展 Export class 允许我添加插件名称并调用 ExportPartCreationPolicy?

这就是我的起点

public class MefExport : ExportAttribute
{
    public MefExport(string exportName)
    {
        string finalExportValue = Helpers.GetPluginName() + exportName;

        new ExportAttribute(finalExportValue, typeof(IController));
    }
}

我认为您无法合理地将这两个属性合二为一。 PartCreationPolicyAttribute 是一个密封的 class,查找该属性的代码将需要该类型。

但是,您可以通过使用计算值调用基数 class 来简化第一位:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
public sealed class MefExportAttribute : ExportAttribute
{
    public MefExportAttribute(string exportName)
        : base(GetContractName(exportName), typeof(IController))
    {
    }

    private static string GetContractName(string exportName)
    {
        return Helpers.GetPluginName() + exportName;
    }
}

(我刚刚复制了 ExportAttributeAttributeUsage 值 - 您可能对此自定义属性有不同的需求。)