Constructor Injection into a custom attribute

299 Views Asked by At

I'm trying the following:

custom attribute:

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    private readonly IUserCodeService _userCodeService;

    public AuthorizeUserAttribute(IUserCodeService userCodeService)
    {
        _userCodeService = userCodeService;
    }

On my controller I use it like:

[AuthorizeUser(Roles = "001, 002")]
public class ChallengesController : Controller

and in Ninject I'm trying it with this:

kernel.Bind<IUserCodeService>().ToConstructor(_ => new WebsealUserCodeService(string.Empty));
kernel.BindFilter<AuthorizeUserAttribute>(FilterScope.Controller, 0)
            .WithConstructorArgumentFromControllerAttribute<AuthorizeUserAttribute>("userCodeService", _ => new WebsealUserCodeService(string.Empty));

But unfortunately it fails to build. When I create an empty constructor in the custom attribute I can build it but when in the overridden AuthorizeCore method I try to call the service it's null (with breakpoints I could see while debugging both constructors were hit and the Roles property is filled in.

While doing investigation I read about the KernelContainer as a usage but that it got discarded in Ninject 3 (it existed in 2.2).

How can I get passed this as I've got another 3 interfaces to inject as well besides this first one.

Is it the correct approach or should I make use of property injection instead?

Update: I decided to not go further with this approach.

0

There are 0 best solutions below