2009-09-18 119 views
6

這是在一個Web應用程序環境中:「會話已關閉!」 - NHibernate

初始請求能夠成功完成,但是任何額外的請求都會從NHibernate框架返回「Session is Closed」響應。我使用的HttpModule方法用下面的代碼:

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

    public void ApplicationBeginRequest(object sender, EventArgs e) 
    { 
     CurrentSessionContext.Bind(SessionFactory.Instance.OpenSession()); 
    } 

    public void ApplicationEndRequest(object sender, EventArgs e) 
    { 
     ISession currentSession = CurrentSessionContext.Unbind(
      SessionFactory.Instance); 

     currentSession.Dispose(); 
    } 

    public void Dispose() { } 
} 

SessionFactory.Instance是我的單身實現,採用FluentNHibernate返回一個ISessionFactory對象。

在我的倉庫類,我嘗試使用下面的語法:

public class MyObjectRepository : IMyObjectRepository 
{ 
    public MyObject GetByID(int id) 
    { 
     using (ISession session = SessionFactory.Instance.GetCurrentSession()) 
      return session.Get<MyObject>(id); 
    } 
} 

這使得在應用程序代碼被稱爲例如:

IMyObjectRepository repo = new MyObjectRepository(); 
MyObject obj = repo.GetByID(1); 

我懷疑我的倉庫代碼應該是怪,但我並不是100%確定我應該使用的實際實施。

我在SO here上發現了類似問題。我也在我的實現中使用WebSessionContext,但是,除了編寫自定義SessionManager之外,沒有提供任何解決方案。對於簡單的CRUD操作,除了內置工具(即WebSessionContext)之外,還需要一個自定義會話提供程序嗎?

回答

4

我沒有測試你的代碼,但是從閱讀,這條線:

using (ISession session = SessionFactory.Instance.GetCurrentSession())

傾銷塊退出後您的會話,然後會話設置/下一次通過上無效。

下面是我們使用我們的應用模型:

ISession session = null; 

try 
{ 
    // Creates a new session, or reconnects a disconnected session 
    session = AcquireCurrentSession(); 

    // Database operations go here 
} 
catch 
{ 
    session.Close(); 
    throw; 
} 
finally 
{ 
    session.Disconnect(); 
}
0

我有一個類似的錯誤。原來我是「新建」我的存儲庫,而不是讓我的IOC容器解決它。

0

使用以下的語句的處置掉或每查詢後關閉會話:

using (ISession session = SessionFactory.Instance.GetCurrentSession()) 

而是使用它沒有「用」字爲:

ISession session = SessionFactory.Instance.GetCurrentSession() 

這爲我工作。