我当前的堆栈是 ASP.NET MVC 4 和 Entity Framework 5.0。我通过 NuGet 安装了 ninject.mvc3,下面显示的代码运行良好:
public class SessionsController : Controller
{
// use "kernel.Bind<MyContext>().ToSelf().InRequestScope();"
// to inject MyContext
private MyContext _context;
public SessionsController(MyContext context)
{
_context = context;
}
[HttpGet]
public ActionResult Login()
{
System.Diagnostics.Debug.WriteLine(_context.Users.Count());
return View();
}
}
}
现在,我想为我的控制器提取一个 BaseController:
public class BaseController : Controller
{
protected MyContext _context;
public BaseController(MyContext context)
{
_context = context;
}
// I don't know what should be write here and
// base controller must have a parameterless constructor
public BaseController()
{
}
}
然后我让 SessionsController 从 BaseController 继承。当我运行代码时,抛出了一个异常
“对象引用未设置为对象的实例。(使用 MyContext)”
我用错了 Ninject 吗?
--UPDATED-- ninject 的 NinjectWebCommon.cs 的代码
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<TelesingContext>().ToSelf().InRequestScope();
}
--UPDATED--编辑后的 SessionsController.cs 代码
public class SessionsController : BaseController
{
[HttpGet]
public ActionResult Login()
{
System.Diagnostics.Debug.WriteLine(_context.Users.Count());
return View();
}
}
}