【发布时间】:2011-04-01 10:21:24
【问题描述】:
我正在使用 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,我猜单例实例在我的应用范围内不会那么单例。
我该怎么做?使用静态变量?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 ninject ninject-extensions