sco*_*kes 10 asp.net-mvc ninject
在MVC的基本控制器中,我有以下注入代码,它工作得很好.
[Inject]
private INavigationRepository navigationRepository { get; set; }
[Inject]
private ISessionService sessionService { get; set; }
Run Code Online (Sandbox Code Playgroud)
我没有出现构建错误,它在"死亡黄页"中显示为"System.NullReferenceException:对象引用未设置为对象的实例".并指向引用navigationRepository的第一行代码.
我可能很少有代码更改,因为它工作,甚至支持这些更改但仍然得到错误.我可以用下面的代码解决它,但我失去注射.有关如何解决这个问题的任何想法?
private INavigationRepository navigationRepository;
private ISessionService sessionService;
public BaseController()
{
navigationRepository = new NavigationRepository();
sessionService = new SessionService(new VolunteerRepository());
}
Run Code Online (Sandbox Code Playgroud)
Rem*_*oor 34
Ninject可以注入私有属性,但必须启用它.
new StandardKernel( new NinjectSettings() { InjectNonPublic = true })
Run Code Online (Sandbox Code Playgroud)
但更好的是不使用属性注入.它应该只在没有办法避免的情况下使用.例如,如果伤害是由其他人创建的(AttributeFilter).否则,可以从外部无意中设置依赖项,并且您需要Inject属性,它将为您提供对IoC容器的引用.我建议在构造函数中添加依赖项并使用构造函数注入.
| 归档时间: |
|
| 查看次数: |
2515 次 |
| 最近记录: |