views:

132

answers:

1

I am using ASP MVC 2 and Nhibernate. I have created an HTTP Module as demonstrated in Summer of NHibernate 13 that looks like so:

public void Init(HttpApplication context)
{
     context.PreRequestHandlerExecute += new EventHandler(Application_BeginRequest);
     context.PostRequestHandlerExecute += new EventHandler(Application_EndRequest);
}

private void Application_BeginRequest(object sender, EventArgs e)
{

    ISession session = StaticSessionManager.OpenSession();
    session.BeginTransaction();
    CurrentSessionContext.Bind(session);
}

private void Application_EndRequest(object sender, EventArgs e)
{
  ISession session = CurrentSessionContext.Unbind(StaticSessionManager.SessionFactory);
  if (session != null)
  try
  {
      session.Transaction.Commit();
   }
   catch (Exception)
   {
       session.Transaction.Rollback();
   }
   finally
   {
       session.Flush();
       session.Close();
    }
}

web.config

<add name="UnitOfWork" type="HttpModules.UnitOfWork"/>

My problem is that Application_EndRequest never gets called on a 404 error so if my view does not render I completely block database access until my flush takes place. I am fairly new to NHibernate so I am not sure if I am missing something.

+3  A: 

You can dispose and rollback the session in application_error. change session.close into session.dispose and check if it's not already disposed.

Paco
Thanks that seemed to work!!
Shane