我開始使用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