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>();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With