In a base controller for MVC, I had the following injection code and it was working perfectly.
[Inject]
private INavigationRepository navigationRepository { get; set; }
[Inject]
private ISessionService sessionService { get; set; }
I do not get build errors and it shows ups in the Yellow Page of Death as "System.NullReferenceException: Object reference not set to an instance of an object." and points to the first line of code that references navigationRepository.
I have may very few code changes since it was working and even backed those changes out but still get the error. I can get around it with the code below but I lose injection. Any thoughts on how to tackle this?
private INavigationRepository navigationRepository;
private ISessionService sessionService;
public BaseController()
{
navigationRepository = new NavigationRepository();
sessionService = new SessionService(new VolunteerRepository());
}
Ninject can inject private properties but it has to be enabled.
new StandardKernel( new NinjectSettings() { InjectNonPublic = true })
But much better is not to use property injection. It should only be used in case there is no way to avoid it. E.g. if the injstance is created by some one else (AttributeFilter). Otherwise the dependencies can be set unintendedly from outside and you need the Inject attribute wich gives you a reference to the IoC container. I'd suggest to add a the dependencies to the constructor and use constructor injection.
Changing the properties to public worked. I guess if it is private, Ninject can not set it.
[Inject]
public INavigationRepository navigationRepository { get; set; }
[Inject]
public ISessionService sessionService { get; set; }
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