我正在使用 MVC3 和 Ninject 启动一个 Web 应用程序。在 Global.asax 文件中我还需要一个依赖项,它需要是一个单例。
我认为它应该是这样的:
public class MvcApplication : NinjectHttpApplication
{
IUserAuthentication _auth;
public MvcApplication()
{
base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest);
}
protected override IKernel CreateKernel()
{
var _kernel = new StandardKernel(new SecurityModule());
_auth = _kernel.Get<IUserAuthentication>();
return _kernel;
}
void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
_auth.ToString();
}
但是后来我看到它在被调用_auth
时为空MvcApplication_AuthenticateRequest
。
然后我尝试这样:
public class MvcApplication : NinjectHttpApplication
{
ItUserAuthentication _auth;
IKernel _kernel;
public MvcApplication()
{
_kernel = new StandardKernel(new SecurityModule());
_auth = _kernel.Get<IUserAuthentication>();
base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest);
}
protected override IKernel CreateKernel()
{
return _kernel;
}
void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
_auth.ToString();
}
但是现在我可以看到构造函数被多次调用,因此我将有几个 IKernel,我猜单例实例在我的应用程序范围内不会那么单例。
我该怎么做?使用静态变量?