在c#中使用MEF时,如何为Export属性创建包装器?
本文关键字:属性 Export 创建 包装 MEF | 更新日期: 2023-09-27 18:15:38
我有一个使用托管可扩展性框架(MEF)和ASP的应用程序。asp.net MVC 5。这个体系结构允许我有一个可插拔的设计,我可以构建多个应用程序,并将它们全部运行到一个主应用程序中。它还允许我有一个中央位置进行身份验证和权限验证/加载。
要使MVC 5与MEF一起工作,每个控制器必须具有唯一的导出值。因此,我必须将这两行代码添加到每个控制器
[Export("SomeUniqueValue1", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]
为了使每个插件的导出值唯一,我喜欢将插件名称连接到导出值。所以我不用上面的两行,而是用这样的
[Export("PluginName.SomeUniqueValue1", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]
现在,我希望通过消除上面的2行代码来节省一些编码时间。我希望像下面这行
[MefExport("SomeUniqueValue1")]
然后MefExport
类,将处理插件名称与提供的名称的连接,并以某种方式调用Export
类和PartCreationPolicy
我如何创建一个类"即MefExport"扩展Export
类,允许我添加插件名称并调用Export
和PartCreationPolicy
?
这是我开始的
public class MefExport : ExportAttribute
{
public MefExport(string exportName)
{
string finalExportValue = Helpers.GetPluginName() + exportName;
new ExportAttribute(finalExportValue, typeof(IController));
}
}
我认为你不能合理地将这两个属性结合为一个。PartCreationPolicyAttribute
是一个密封类,查找该属性的代码将精确地需要该类型。
[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;
}
}
(我只是复制了ExportAttribute
的AttributeUsage
值-您可能对这个自定义属性有不同的需求)