I use NHibernate's built in contextual sessions. You can read about them here:
http://nhibernate.info/doc/nhibernate-reference/architecture.html#architecture-current-session
Here is an example of how I use this:
public class SessionFactory
{
protected static ISessionFactory sessionFactory;
private static ILog log = LogManager.GetLogger(typeof(SessionFactory));
//Several functions omitted for brevity
public static ISession GetCurrentSession()
{
if(!CurrentSessionContext.HasBind(GetSessionFactory()))
CurrentSessionContext.Bind(GetSessionFactory().OpenSession());
return GetSessionFactory().GetCurrentSession();
}
public static void DisposeCurrentSession()
{
ISession currentSession = CurrentSessionContext.Unbind(GetSessionFactory());
currentSession.Close();
currentSession.Dispose();
}
}
In addition to this I have the following in my hibernate config file:
<property name="current_session_context_class">thread_static</property>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…