Ninject Binding Attribute to Filter with Constructor Arguments

I have figured it out (thanks to Remo’s directions and documentation).

Use the appropriate .WithConstructorArgument extension whether you are binding to a Controller or Action filter. For example binding my action filter looks like this:

kernel.BindFilter<AuthorizationFilter>(FilterScope.Action, 0)
      .WhenActionMethodHas<RequireRolesAttribute>()
      .WithConstructorArgumentFromActionAttribute<RequireRolesAttribute>("requiredRoles", o => o.RequiredRoles);

Once I understood the Func<> signature, it all became clear. The best way I found to handle this was to

  1. make the extension type-specific for my attribute

    .WithConstructorArgumentFromActionAttribute<TAttribute>()
    
  2. fetch the value from the callback object (your attribute) via lambda:

    ("argumentName", o => o.PropertyName)
    

Leave a Comment