How to use dependency injection with an attribute?

前端 未结 2 1123
长发绾君心
长发绾君心 2020-11-28 08:55

In an MVC project I\'m creating I have the following RequirePermissionAttribute that gets put on any action that needs specific permissions (it\'s been simplifi

2条回答
  •  悲&欢浪女
    2020-11-28 09:47

    I originally thought this was not possible, but I stand corrected. Here's an example with Ninject:

    http://codeclimber.net.nz/archive/2009/02/10/how-to-use-ninject-to-inject-dependencies-into-asp.net-mvc.aspx

    Update 2016-10-13

    This is a pretty old question by now, and frameworks have changed quite a bit. Ninject now allows you to add bindings to specific filters based on the presence of specific attributes, with code like this:

    // LogFilter is applied to controllers that have the LogAttribute
    this.BindFilter(FilterScope.Controller, 0)
         .WhenControllerHas()
         .WithConstructorArgument("logLevel", Level.Info);
     
    // LogFilter is applied to actions that have the LogAttribute
    this.BindFilter(FilterScope.Action, 0)
         .WhenActionHas()
         .WithConstructorArgument("logLevel", Level.Info);
     
    // LogFilter is applied to all actions of the HomeController
    this.BindFilter(FilterScope.Action, 0)
         .WhenControllerTypeIs()
         .WithConstructorArgument("logLevel", Level.Info);
     
    // LogFilter is applied to all Index actions
    this.BindFilter(FilterScope.Action, 0)
         .When((controllerContext,  actionDescriptor) =>
                    actionDescriptor.ActionName == "Index")
         .WithConstructorArgument("logLevel", Level.Info);
    

    This is in keeping with the principle, argued by Mark Seeman and by the author of Simple Injector, which is that you should keep the logic of your action filter separate from the custom attribute class.

    MVC 5 and 6 also make it far easier to inject values into attributes than it used to be. Still, separating your action filter from your attribute is really the best approach to take.

提交回复
热议问题