I'm with you and not really understanding the best way of managing sessions.
I found this in one of the tutorials and this is what I have started to use, mainly because i understand what it's doing.
Code:
public sealed class NHibernateSessionHelper
{
private const string CurrentSessionKey = "nhibernate.current_session";
private static readonly ISessionFactory sessionFactory;
static NHibernateSessionHelper()
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.AddAssembly("NHibernate.Examples");
sessionFactory = cfg.BuildSessionFactory();
}
public static ISession GetCurrentSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
currentSession = sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}
return currentSession;
}
public static void CloseSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
// No current session
return;
}
currentSession.Close();
context.Items.Remove(CurrentSessionKey);
}
public static void CloseSessionFactory()
{
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
}
I tend to have a wrapper this is a mathod for a Company class.
Code:
public IList GetAllCompanies()
{
ISession session = NHibernateSessionHelper.GetCurrentSession();
ITransaction tx = session.BeginTransaction();
IQuery query = session.CreateQuery("from Company as C where C.Active=6");
IList u = query.List();
tx.Commit();
session.Close();
NHibernateSessionHelper.CloseSession();
return u;
}
does this look ok?
I don't get the:
Code:
session.Close(); // closing in local session
NHibernateSessionHelper.CloseSession(); // closing the static version.