在MVC的基本控制器中,我有以下注入代码,它运行正常。
[Inject]
private INavigationRepository navigationRepository { get; set; }
[Inject]
private ISessionService sessionService { get; set; }
我没有出现构建错误,它在“死亡黄页”中显示为“System.NullReferenceException:对象引用未设置为对象的实例”。并指向引用navigationRepository的第一行代码。
我可能很少有代码更改,因为它工作,甚至支持这些更改但仍然得到错误。我可以用下面的代码解决它,但我失去注射。有关如何解决这个问题的任何想法?
private INavigationRepository navigationRepository;
private ISessionService sessionService;
public BaseController()
{
navigationRepository = new NavigationRepository();
sessionService = new SessionService(new VolunteerRepository());
}
答案 0 :(得分:34)
Ninject可以注入私有属性,但必须启用它。
new StandardKernel( new NinjectSettings() { InjectNonPublic = true })
但更好的是不使用属性注入。它应该只在没有办法避免的情况下使用。例如。如果伤害是由其他人创造的(AttributeFilter)。否则,可以从外部无意中设置依赖项,并且您需要Inject属性,它将为您提供对IoC容器的引用。我建议在构造函数中添加依赖项并使用构造函数注入。
答案 1 :(得分:1)
将属性更改为公共工作。我猜如果它是私有的,Ninject就无法设置它。
[Inject]
public INavigationRepository navigationRepository { get; set; }
[Inject]
public ISessionService sessionService { get; set; }