How do I resolve Dependency Injection in MVC Filter attributes

前端 未结 4 494
灰色年华
灰色年华 2021-02-07 15:36

I have a custom attribute class derived from AuthorizationAttribute, which performs custom security on controller actions. The OnAuthorizationCore method depends on various othe

4条回答
  •  有刺的猬
    2021-02-07 16:14

    Constructor injection seems to be impossible w/o changing way of filter registration.

    Even in Asp.Net Mvc3:

    One place where dependency injection has been difficult in the past is inside the filter attributes themselves. Because the .NET framework runtime is actually responsible for creating these attribute instances, we cannot use a traditional dependency injection strategy.

    So - next best thing is property injection (Mvc3 provides some support for that out of the box).

    Here's a how to for doing that manually.

    I personally use MvcExtensions. I'm fine with registering them in different way. Here's usage.

    Another thing You might want to investigate is MvcTurbine project. In contrast to MvcExtensions project which is more general - MvcTurbine is primarily for providing dependency injection support.

提交回复
热议问题