Hi guys!
I hope you can help me with a session-realted issue I have with NHibernate.
I'm using NHibernate version 2.0GA with SQL Server 2005 in an ASP.NET project.
When I handle the session management in the business methods, everything works as expected. For example here is a business method:
Code:
public override void Send()
{
try
{
using (var session = NHibernateHelper.OpenSession())
{
using (session.BeginTransaction())
{
CurrentSessionContext.Bind(session);
var customerServiceMailRepository = RepositoryFactory.GetCustomerServiceMailRepository();
customerServiceMailRepository.MakePersistent(this);
session.Transaction.Commit();
}
}
}
catch (Exception ex)
{
throw new BusinessException("Error accessing database", ex);
}
finally
{
CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
}
}
This works nicely. But obviously I don´t like the business layer to handle the sessions, so I did this HttpModule:
Code:
public class NHibernateCurrentSessionWebModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += Application_BeginRequest;
context.EndRequest += Application_EndRequest;
}
private void Application_EndRequest(object sender, EventArgs e)
{
var session = CurrentSessionContext.Unbind(NHibernateHelper.SessionFactory);
if (session != null)
{
try
{
session.Transaction.Commit();
}
catch (Exception)
{
session.Transaction.Rollback();
HttpContext.Current.Server.Transfer("error.aspx", true);
}
finally
{
session.Close();
}
}
}
private void Application_BeginRequest(object sender, EventArgs e)
{
var session = NHibernateHelper.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
public void Dispose()
{
}
}
I got this HttpModule code from the "NHibernate in Action" book.
When I add this module to the web.config file, and use it, things doesn´t work as expected. When using it nothing gets saved to the database, and when I try to access the table via SQL Server Management Studio I time out until I close the development server (but I can access other tables without any problems what so ever).
What am I doing wrong?