Do NOT hold static session in nhibernate

Refer to http://www.cnblogs.com/netgarden/archive/2006/11/23/570129.html

Every data access strategy after server-side cursors has had as a goal minimizing the length of time an application holds open a connection, and NHibernate is no different. Therefore, having a static Session sitting around open and available is a poor strategy.

Instead, you can use disconnected Sessions. You can still create a shared Session object (either instance-available or truly static) for use in your methods. However, instead of leaving it open, or closing it in every method, you can follow the following pattern:

public IList getClasses(){
IList classes = null;
try{
  // session is declared in instance scope
  session.Reconnect();
  ITransaction tx = session.BeginTransaction();
  classes = session.CreateCriteria(
  typeof(UniversityClass)).List();
}
catch (Exception ex){
  // handle exception
}
finally{
  session.Flush();
  session.Disconnect();
}
return classes;
}
posted @ 2012-09-06 10:28  webglcn  阅读(192)  评论(0编辑  收藏  举报