2

我有一個簡單的自定義FilterAttribute,我用它來裝飾各種ActionMethods是否可以在ASP.NET MVC FilterAttribute上使用依賴注入/ IoC?

例如。

[AcceptVerbs(HttpVerbs.Get)] 
[MyCustomFilter] 
public ActionResult Bar(...) 
{ ... } 

現在,我想一些記錄添加到這個CustomFilter行動..所以是一個好孩子,我使用DI/IoC ......,因此希望使用此模式爲我定製FilterAttribute

所以,如果我有以下的...

ILoggingService 

,並希望增加這是我的自定義FilterAttribute ..我不知道怎麼樣。像,很容易讓我做下面...

​​

但是編譯器錯誤說法,其中裝飾的屬性我ActionMethod(以上所列...)要求1 ARG ..所以我只是不知道該怎麼辦:(

回答

3

我有物業注射Ninject和工作Ninject.Web.MVC

只要您從Ninject.Web.MVC獲得控制器工廠,它就相當簡單。

E.g.

public class EventExistsAttribute : FilterAttribute, IActionFilter 
{ 
    [Inject] 
    public IEventRepository EventRepo { private get; set; } 

    public void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     //Do stuff 
    } 

    public void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     //Do something else if you so wish... 
    } 
} 

它具有實質上具有「隱藏」依賴性的缺點,可以這麼說...但對此你可以做的事情不多。

HTHS,
查爾斯

2

你需要編寫自己的IActionInvoker,做財產注射。有想法看看this後吉米·博加德。

2

是的,它可以使用依賴注入在FilterAttribute。但是不可能在FilterAttribute上使用構造函數注入。這不是ASP.NET MVC的限制,它是所有.Net代碼的共同之處,如the values passed into an attributes constuctor are limited to simple types

[MyFilter(ILogger logger)] // this will not compile 
public ActionResult Index() 
{ 
    return View(); 
} 

因此,通常的做法是讓你的依賴濾波器的財產,如@ Charlino的例子。然後你可以使用屬性注入。您可以使用Ninject來裝飾過濾器屬性,如@ Charlino的示例中所示。或者按照@mrydengren的建議,您可以在ControllerActionInvoker的自定義子類中執行此操作。