Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ninject Stopped Injecting My Properties

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());
    }
like image 304
scottrakes Avatar asked Nov 27 '10 17:11

scottrakes


2 Answers

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.

like image 91
Remo Gloor Avatar answered Nov 16 '22 00:11

Remo Gloor


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; }
like image 22
scottrakes Avatar answered Nov 16 '22 02:11

scottrakes