[英]How can I create a wrapper for the Export attribute when using MEF with C#?
我有一個使用托管擴展框架(MEF)和ASP.NET MVC 5的應用程序。此體系結構允許我進行可插拔的設計,可以在其中構建多個應用程序並將它們全部運行到一個主應用程序中。 這也使我可以在一個中心位置進行身份驗證和權限驗證/加載。
為了使MVC 5與MEF一起使用,每個控制器必須具有唯一的導出值。 因此,我必須將這兩個行代碼添加到每個控制器中
[Export("SomeUniqueValue1", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]
為了使每個插件唯一的導出值,我想將插件名稱連接到導出值。 因此,我將不使用上面的兩行,而是使用類似的內容
[Export("PluginName.SomeUniqueValue1", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]
現在,我希望通過消除上面的兩行代碼來節省一些編碼時間。 我希望下面的內容
[MefExport("SomeUniqueValue1")]
然后, MefExport
類將處理插件名稱與提供的名稱的連接,並以某種方式調用Export
類和PartCreationPolicy
如何創建擴展Export
類的類“ ie MefExport”,允許我添加插件名稱並調用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
值-您對此自定義屬性可能有不同的需求。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.