簡體   English   中英

屬性注入到動作過濾器

[英]Property Injection into an Action Filter

我正在嘗試讓“屬性注入”在“自定義操作過濾器”屬性上運行。 它正在按預期的方式運行,但是,我想在屬性本身上使用DI。 我的篩選器看起來像這樣

[AttributeUsage(AttributeTargets.Class)]
public sealed class HeaderFilterAttribute : ActionFilterAttribute
{
    public IMarketService MarketService
    { get; set; }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var view = (ViewResultBase)filterContext.Result;

        if (view != null)
        {
            BaseViewModel viewModel = view.ViewData.Model as BaseViewModel;
            if (viewModel != null)
                viewModel.Header = GetHeaderScript();
        }
        base.OnActionExecuted(filterContext);
    }

   private string GetHeaderScript()
   {
     //Use MarketService here and return header script
     return "script";
   }
}

這就是我在BootStrapper類中使用StructureMap配置屬性的方式。

            //HeaderFilterAttribute
        IMarketRepository marketRepository = new SqlMarketRepository();
        IMarketService marketService = new MarketService(marketRepository);
        ObjectFactory.Container.Configure(r => r.ForConcreteType<HeaderFilterAttribute>().
                                          Configure.WithProperty("MarketService").
                                          EqualTo(marketService));

我的問題是我無法訪問SqlMarketRepository,因為我所有的具體類型都是通過DI注入的,我真的不想在我的引導程序中使用具體類型。 因此,現在的最終問題是,如何不借助上述方法將MarketService注入Filter屬性? :)

在您的ObjectFactory.Initialize()調用中,添加以下行:

SetAllProperties(x => x.OfType<IMarketService>());

這會將配置好的IMarketService實例注入到從容器中檢索到的任何對象上的IMarketService類型的任何屬性中。

我認為您需要一個可解決過濾器的自定義操作調用程序實現。 您可以從我公司的實施中提取一個Windsor示例(下降約1/2倍)。 網上應該還有更多可用的內容。 我知道我在這個網站上看到了一些。

PS。 我注意到您正在使用基本視圖模型填充標頭。 我建議將ViewData []集合與靜態鍵一起使用,而不要在視圖模型中使用繼承。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM