后來,我看了Cuyahoga開源項目中他的Session管理,他使用的“session-per-request”這種模式。 從字面上理解就是他為每個Request創(chuàng)建一個Session,直到這個請求銷毀,那么這個Session也就Close了。 而Cuyahoga他的做法和session-per-request有點不同地方就是,他為每個Request都創(chuàng)建了一個CoreRepository對象,CoreRepository是系統(tǒng)所需要的數(shù)據(jù)處理服務的類。 他的做法是先創(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(); } }