我正在使用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();
}
但后来我发现在调用MvcApplication_AuthenticateRequest
时_auth
为空。
然后我尝试了这样的代码:
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实例,我想单例实例在我的应用程序范围内不会是真正的单例。
我该怎么做?使用静态变量吗?