nhibernate中的session,在我的理解似乎就相當于數(shù)據(jù)庫中連接。因為它也有open/close的方法,我沒有研究nhibernate的源碼,不知道這種理解是否有誤?我在網(wǎng)上搜了很多的關(guān)于session的管理,大多都是在我需要數(shù)據(jù)庫操作的時候,就opensession(),操作完后就closesession().這有點擬似如我們剛開始學習ado.net的時候,要connection對象open(),數(shù)據(jù)處理完后就close().但是這里就帶來了一個弊端,因為connection的頻繁的開關(guān)是非常消耗系統(tǒng)資源的。我記得以前在制作一個數(shù)據(jù)的錄入界面的時,因為這個錄入的界面數(shù)據(jù)元素比較多,而且很多dropdownlist需要在數(shù)據(jù)庫中讀取數(shù)據(jù)并綁定。
這樣在該頁面的page_load中需要調(diào)用相應(yīng)對象的方法一一從數(shù)據(jù)庫中檢索數(shù)據(jù)綁定dropdownlist.因為我們這些對象的方法都是使用獨立的connection,都有自己的connection的open和close。所以,導致這個頁面一打開就需要等待好長的時間,比較慢。后來我們將這些需要綁定dropdownlist的數(shù)據(jù)通過一個數(shù)據(jù)處理成一個dataset,并將dataset中的datatable與dropdownlist綁定。這樣只需要一次的connection的open/close.頁面快了好多。
所以,我覺得上述的session的管理辦法不是很妥當。
后來,我看了cuyahoga開源項目中他的session管理,他使用的“session-per-request”這種模式。從字面上理解就是他為每個request創(chuàng)建一個session,直到這個請求銷毀,那么這個session也就close了。而cuyahoga他的做法和session-per-request有點不同地方就是,他為每個request都創(chuàng)建了一個corerepository對象,corerepository是系統(tǒng)所需要的數(shù)據(jù)處理服務(wù)的類。他的做法是先創(chuàng)建了httpmodule(nhsessionmodule)用來創(chuàng)建corerepository對象和銷毀corerepository對象,如下:
private void context_beginrequest(object sender, eventargs e)
{
// create the repository for core objects and add it to the current httpcontext.
corerepository cr = new corerepository(true);
httpcontext.current.items.add("corerepository", cr);
}
private void context_endrequest(object sender, eventargs e)
{
// close the nhibernate session.
if (httpcontext.current.items["corerepository"] != null)
{
corerepository cr = (corerepository)httpcontext.current.items["corerepository"];
cr.closesession();
}
}
這樣在每次請求的時候,會自動創(chuàng)建corerepository對象,當請求完畢后,就closesession(),在程序中通過httpcontext.current.items["corerepository"]就能獲取corerepository對象了。
這樣也就變相的管理了nhibernate中的session,也就達到了“session-per-request”的這種模式。
詳細的講解: 通過實現(xiàn)ihttpmodule初始化nhibernate的session
這種方式比上面的那個每次操作都需要創(chuàng)建session,性能和速度應(yīng)該提高了不少,接著我就想,每個請求都創(chuàng)建session,是不是我們可以象創(chuàng)建connection pool一樣,也創(chuàng)建一個session pool,這樣就每次請求的時候不是直接創(chuàng)建session,而是在我們的session pool中拿已經(jīng)創(chuàng)建好的session,這樣效率不是更好?!
新聞熱點
疑難解答
圖片精選