2011-02-16 75 views
12

我最近試用了NinjectNinject.Web.Mvc擴展名,我注意到了一些特殊的東西,雖然沒有打破,但令人困惑。Ninject和OnePerRequestModule

NinjectHttpApplication抽象類,沒有定義構造函數如下..

/// <summary> 
    /// Initializes a new instance of the <see cref="NinjectHttpApplication"/> class. 
    /// </summary> 
    protected NinjectHttpApplication() 
    { 
     this.onePerRequestModule = new OnePerRequestModule(); 
     this.onePerRequestModule.Init(this); 
    } 

我把一個調試器斷點這裏,這被稱爲幾次。我找不到任何真實的文檔。在實現代碼中,這條線引起了我的注意。

  if (kernel.Settings.Get("ReleaseScopeAtRequestEnd", true)) 
      { 
       OnePerRequestModule.StartManaging(kernel); 
      } 

我的問題如下...

  • 什麼是OnePerRequestModule
  • 爲什麼這個構造被稱爲多次?
  • 這個StartManaging方法的目的是什麼,如果構造函數被多次調用?
+0

相關:http://stackoverflow.com/questions/15778324/do-i-need-to-register-ninject-oneperrequestmodule-with-ninject-web-mvc-3-0/15786866# – 2013-04-03 12:28:57

回答

13

OnePerRequestModule除去從內核的Cache每個HTTP請求完成時InRequestScope() d對象。

因爲IIS創建了多個時間,所以多次調用該ctor。一個NinjectHttpApplication一次只能處理一個請求。所以IIS每個線程(至少)生成一個實例。

StartManaging告訴所有OnePerRequestModules他們應該在請求結束之後從指定的內核釋放InRequestScoped對象。

+0

所以這是一些東西我可以保持完好嗎?這不是我需要擔心的事情嗎? – Ciel 2011-02-17 16:22:22