长篇小说,我试图使用ELMAH与MVC 2和Ninject,我需要使用无参数的构造函数.我在这里创建了一个初步的帖子:
Using a parameterless controller constructor with Ninject?
我被建议使用物业注入而不是构造器注入.所以我从此移开:
public class DepartmentsController : Controller { private IDepartmentsRepository departmentsRepository; public DepartmentsController(IDepartmentsRepository departmentsRepository) { this.departmentsRepository = departmentsRepository; } ... }
到这个:
public class DepartmentsController : Controller { private IDepartmentsRepository _departmentsRepository; [Inject] public IDepartmentsRepository DepartmentsRepository { get { return _departmentsRepository; } set { _departmentsRepository = value; } } ... }
但是在我的其他控制器功能中,无论我尝试访问DepartmentsRepository还是_departmentsRepository,当我尝试访问它时,我得到的对象引用未设置为对象的一个实例错误.
还有什么我需要做的吗
解决方法
我也有类似的问题.看看我的问题:
Using Ninject with Membership.Provider.
基本上,当你初始化DepartmentsController时,你需要注入(即你的部门控制器进入你的Ninject内核,所以它的东西像:
public class DepartmentsController : Controller { private IDepartmentsRepository _departmentsRepository; [Inject] public IDepartmentsRepository DepartmentsRepository { get { return _departmentsRepository; } set { _departmentsRepository = value; } } public DepartmentsController() { NinjectHelper.Kernel.Inject(this); } }
在这种情况下,NinjectHelper获取当前的Ninject Kernel.