我开始使用MVC3和Ninject创建Web应用程序。在Global.asax文件中还需要一个依赖项,该文件需要是单例。在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,我想这个单实例不会那么单在我的应用范围内。
我应该怎么做?使用静态变量?
这不是一个杀死事实,即在每个请求中调用DependencyResolver。 – vtortola 2011-04-15 09:57:53
我不这么认为,@Remo应该能够告诉你比我多,但是因为我在构造函数中的大部分控制器中注入了我的_authService,它可能会做同样的事情,并且不会“花费”那个mutch ... – VinnyG 2011-04-15 14:34:12
太棒了。我认为这将直到@Remo解决问题。太感谢了。 – vtortola 2011-04-16 14:51:21