Attribute filter attribute for dependency injection to accept parameters in the constructor

I follow the ninject filter attribute setting on this page .

For them they have:

.WithConstructorArgumentFromControllerAttribute<LogAttribute>( "logLevel", attribute => attribute.LogLevel); 

The second parameter expects Func<LogAttribute, object> callback . Their actual parameter list is configured as follows:

 Log(LogLevel = Level.Debug) 

But my filter attribute is configured as follows:

 public class AuthAttribute : FilterAttribute { } public class AuthFilter : IAuthorizationFilter { private readonly IUserService userService; private string[] roles; //Stuck on the constructor also. How do I accept params? public AuthFilter(IUserService userService, params string[] roles) { this.userService = userService; this.roles = roles; } public void OnAuthorization(AuthorizationContext filterContext) { throw new NotImplementedException(); } } 

Somehow this is wrong. Because I want my filter to look like this:

 [Auth("Admin", "Contrib")] 

My bindings:

  kernel.BindFilter<AuthFilter>(FilterScope.Controller, 0) .WhenControllerHas<AuthAttribute>() .WithConstructorArgumentFromControllerAttribute<AuthAttribute>("roles", /*Stuck here*/) 
+6
asp.net-mvc asp.net-mvc-3 ninject
Jun 01 2018-11-11T00:
source share
1 answer

You need to make the roles in the property in your attribute.

Attribute

 public class AuthAttribute : FilterAttribute { public string[] Roles { get; set; } public AuthAttribute(params string[] roles) { this.Roles = roles; } } 

Filter:

 public class AuthFilter : IAuthorizationFilter { private readonly IUserService userService; private readonly string[] roles; public AuthFilter(IUserService userService, string[] roles) { this.userService = userService; this.roles = roles; } public void OnAuthorization(AuthorizationContext filterContext) { //do stuff } } 

controller

  [AuthAttribute("a", "b")] public class YourController : Controller { } 

Binding:

 kernel.BindFilter<AuthFilter>(FilterScope.Controller, 0) .WhenControllerHas<AuthAttribute>() .WithConstructorArgumentFromControllerAttribute<AuthAttribute>("roles", attribute => attribute.Roles); 
+15
Jun 01 2018-11-18T00:
source share



All Articles