關於ISession的聲明。NHibernate - ISession
我們是否應該在每次使用它時關閉會話,還是應該保持打開狀態?我想問這是因爲在NHibernate(nhforge.org)手冊中,他們建議我們在Application_Start中聲明一次,但我不知道我們是否應該在每次使用時關閉它。
感謝
關於ISession的聲明。NHibernate - ISession
我們是否應該在每次使用它時關閉會話,還是應該保持打開狀態?我想問這是因爲在NHibernate(nhforge.org)手冊中,他們建議我們在Application_Start中聲明一次,但我不知道我們是否應該在每次使用時關閉它。
感謝
你可以把一個單一的靜態參照ISessionFactory,它可以在被的Application_Start確實實例化的web應用程序。
但是,ISession不能保持打開狀態,不能在兩個或多個請求之間共享。您應該採用「每個請求一個會話」模式,它允許您爲每個HTTP請求構建一個ISession,並在請求處理完畢後(假設您正在編寫Web應用程序)安全地進行處理。
例如,代碼處理NHibernate的會議在你的項目可能是這樣的:
public static class NHibernateHelper {
static ISessionFactory _factory;
public static NHibernateHelper(){
//This code runs once when the application starts
//Use whatever is needed to build your ISessionFactory (read configuration, etc.)
_factory = CreateYourSessionFactory();
}
const string SessionKey = "NhibernateSessionPerRequest";
public static ISession OpenSession(){
var context = HttpContext.Current;
//Check whether there is an already open ISession for this request
if(context != null && context.Items.ContainsKey(SessionKey)){
//Return the open ISession
return (ISession)context.Items[SessionKey];
}
else{
//Create a new ISession and store it in HttpContext
var newSession = _factory.OpenSession();
if(context != null)
context.Items[SessionKey] = newSession;
return newSession;
}
}
}
此代碼大概是目前爲止簡單,並沒有經過測試(也其實編譯),但它應該工作。爲了更安全地處理會話,您還可以使用IoC容器(例如Autofac),並根據HTTP請求註冊您的ISessions(Autofac將在這種情況下爲您處理所有事情)。
會議結束後,你應該關閉它們。有多種可能的方式來管理會話的生命週期,並選擇適合每種情況的特定方法。 「工作單元」和「每個請求的會話」是兩種最常用的會話生命週期管理模式。
在Application_Start中,您應該創建SessionFactory,而不是Session。 SessionFactory不需要關閉。