NHibernate Version: 2.1
I'm using what seems to be a pretty standard HttpModule approach to implementing per-request sessions in an ASP.NET+NHibernate application. I'm trying to leverage WebSessionContext
, but it doesn't seem to be working correctly. Specifically, everything works brilliantly for the first request on the application, but additional requests result in a "Session is closed!" exception any time the session is used. Resetting the application pool allows another request to succeed, then more "Session is closed!".
There are a few moving pieces, but I don't know enough about how the context is managed to narrow it down so...here's everything!
In web.config:
<property name="current_session_context_class">
NHibernate.Context.WebSessionContext, NHibernate
</property>
(I've tried setting it to just 'web', too, with the same result.)
The module, confirmed to be configured correctly:
public class NHibernateSessionModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
Debug.WriteLine("NHibernateSessionModule.Init()");
context.BeginRequest += context_BeginRequest;
context.EndRequest += context_EndRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
Debug.WriteLine("NHibernateSessionModule.BeginRequest()");
var session = NHibernateHelper.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
void context_EndRequest(object sender, EventArgs e)
{
Debug.WriteLine("NHibernateSessionModule.EndRequest()");
var session = NHibernateHelper.GetCurrentSession();
if (session != null)
{
try
{
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Commit();
}
catch (Exception ex)
{
session.Transaction.Rollback();
throw new ApplicationException("Error committing database transaction", ex);
}
finally
{
session.Close();
}
}
CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
}
}
And my little helper:
public class NHibernateHelper
{
public static readonly ISessionFactory SessionFactory;
static NHibernateHelper()
{
try
{
Configuration cfg = new Configuration();
cfg.AddAssembly(Assembly.GetCallingAssembly());
SessionFactory = cfg.Configure().BuildSessionFactory();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw new ApplicationException("NHibernate initialization failed", ex);
}
}
public static ISession GetCurrentSession()
{
return SessionFactory.GetCurrentSession();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}