How do I resolve Dependency Injection in MVC Filter attributes

前端 未结 4 524
灰色年华
灰色年华 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:28

    The ExtensibleActionInvoker claims to be able to perform property injection on action filters.

    Correct - but don't confuse action filters with the attributes that might not implement them. The cleanest way to approach this in ASP.NET MVC is to split responsibilities, even though the MVC framework allows you to combine them.

    E.g., use a pair of classes - an attribute class that holds data only:

    // Just a regular old attribute with data values
    class SomeAttribute : Attribute { ... }
    

    And a filter that has dependencies injected:

    // Gets dependencies injected
    class SomeFilter : IActionFilter { ... }
    

    SomeFilter just uses the typical approach of getting the SomeAttribute attribute from the controller or action method via GetCustomAttributes() to do whatever work is needed.

    You can then use ExtensibleActionInvoker to wire up the filter:

    builder.RegisterControllers(...).InjectActionInvoker();
    builder.RegisterType().As();
    builder.RegisterType().As();
    

    It might be a little more code than you'd write using the attribute-as-filter approach, but the quality of the code will be better in the long run (e.g. by avoiding the limitations of attributes and the awkwardness of the Service Locator solutions.)

提交回复
热议问题