Ninject 2 Property Injection for ActionFilterAttribute not working
Asked Answered
T

1

7

I have a method attribute which expects several properties to be injected by Ninject 2, but userSession and jobRepository are coming up as null:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class JobAttribute : ActionFilterAttribute {
    [Inject]
    private IUserSession userSession;

    [Inject]
    private IJobRepository jobRepository;

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        var filter = new JobFilter(userSession, jobRepository);

        filter.OnActionExecuting(filterContext);
    }
}

And here is the method in the controller:

[AcceptGet, Job]
public ActionResult Dimensions(Job job) {
    return View(job.Building);
}

I know I have the setup working because if I use constructor injection on the controller the controller's parameters get injected. That doesn't help me much for attributes though that need to use property injection. Am I missing something here?

Here are the pertinent potions of Global.asax.cs:

public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication {
    protected override void OnApplicationStarted() {
        RegisterRoutes(RouteTable.Routes);
        RegisterAllControllersIn(Assembly.GetExecutingAssembly());
    }

    ...snip...

    protected override IKernel CreateKernel() {
        return new StandardKernel(
            new RepositoryConfiguration(),
            new AuthenticationModule(),
            new AutoMapperConfiguration()
        );
    }
}

public class RepositoryConfiguration : NinjectModule {
    public override void Load() {
        Bind<ICustomerRepository>().To<CustomerRepository>();
        Bind<IJobRepository>().To<JobRepository>();
    }
}

public class AuthenticationModule : NinjectModule {
    public override void Load() {
        Bind<MbdQuote.Core.AppService.IUserSession>().To<UserSession>();
    }
}
Tupi answered 15/2, 2010 at 23:6 Comment(0)
H
13

Ninject2 does not do field injection, change them to properties with a public setter.

class JobAttribute : ActionFilterAttribute {
    [Inject]
    public IUserSession UserSession
    { set; private get; }

    [Inject]
    public IJobRepository JobRepository
    { set; private get; }
}

From the Ninject 2 Beta announcement:

Things that were in Ninject 1.x that are not in Ninject 2:

  • Field injection: Ninject 2’s injection is now driven by expression trees, and in .NET 3.5 there is no way to set field values with an expression tree. Since this is a bad practice anyway, I decided to cut it.
Hyperon answered 15/2, 2010 at 23:12 Comment(2)
That's it! The properties have to have a public setter to be injected by Ninject. I would not have thought that would matter.Tupi
Thanks for this answer - I was searching everywhere for the solution to this exact problem.Yaekoyael

© 2022 - 2024 — McMap. All rights reserved.