2010-03-14 111 views
5

我的web應用程序的解決方案包括3個項目:依賴注入有多遠?

  1. Web應用程序(ASP.NET MVC)
  2. 業務邏輯層(類庫)
  3. 數據庫層(實體框架)

我想使用Ninject管理Database LayerEntity Framework生成的DataContext的生存期。

業務邏輯層由引用存儲庫(位於數據庫層中)的類組成,我的ASP.NET MVC應用引用業務邏輯層的服務類來運行代碼。每個庫創建從實體框架

庫的MyDataContext對象的實例

public class MyRepository 
{ 
    private MyDataContext db; 
    public MyRepository 
    { 
     this.db = new MyDataContext(); 
    } 

    // methods 
} 

業務邏輯類

public class BizLogicClass 
{ 
    private MyRepository repos; 
    public MyRepository 
    { 
      this.repos = new MyRepository(); 
    } 

    // do stuff with the repos 
} 

威爾Ninject處理的MyDataContext壽命儘管從Web冗長的依賴鏈應用程序到數據層?

回答

3

編輯

我有前一段時間一些問題,但現在它似乎工作:

Bind<CamelTrapEntities>().To<CamelTrapEntities>().Using<OnePerRequestBehavior>(); 

而不是使用HTTP模塊,你可以使用OnePerRequestBehavior,它會照顧處理當前請求中的上下文。

EDIT 2

OnePerRequestBehavior需要在web.config中註冊,因爲它取決於太多的HttpModule:

在IIS6:

<system.web> 
    <httpModules> 
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/> 
    </httpModules> 
</system.web> 

隨着IIS7:

<system.webServer> 
    <modules> 
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/> 
    </modules> 
</system.webServer> 

上一個回答

當你不需要的時候處理上下文是你的責任。 ASP.NET中最流行的方式是每個請求都有一個ObjectContext。我這樣做具有的HttpModule:

public class CamelTrapEntitiesHttpModule : IHttpModule 
{ 
    public void Init(HttpApplication application) 
    { 
     application.BeginRequest += ApplicationBeginRequest; 
     application.EndRequest += ApplicationEndRequest; 
    } 

    private void ApplicationEndRequest(object sender, EventArgs e) 
    { 
     ((CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]).Dispose(); 
    } 

    private static void ApplicationBeginRequest(Object source, EventArgs e) 
    { 
     HttpContext.Current.Items[@"CamelTrapEntities"] = new CamelTrapEntities();    
    } 
} 

這是注射規則:

Bind<CamelTrapEntities>().ToMethod(c => (CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]); 

我的倉庫發生的ObjectContext中構造函數:

public Repository(CamelTrapEntities ctx) 
{ 
    _ctx = ctx; 
} 
+0

是什麼「似乎工作」是什麼意思? – jfar 2010-03-14 02:46:07

+0

@jfar:我在幾分鐘前檢查並調用kernel.Get <>兩次給了我請求中的同一個實例。我不記得之前有什麼問題,但不知何故,我決定不使用它。與此同時,我下載了新的消息來源,但直到今天才進行檢查,所以它得到了正確的修正。 – LukLed 2010-03-14 02:54:00

3

只是想提一提,Autofac with the ASP.Net integration有要求的壽命支持內置。在RequestContainer中解析實例,它們將在請求結束時處理(如果實現IDisposable)。

你應該讓你的班迪友好,但:

public class MyRepository 
{ 
    private MyDataContext db; 
    public MyRepository(MyDataContext context) 
    { 
     this.db = context; 
    } 

    // methods 
} 

public class BizLogicClass 
{ 
    private MyRepository repos; 
    public BizLogicClass(MyRepository repository) 
    { 
      this.repos = repository; 
    } 

    // do stuff with the repos 
}