Hello,
I have implemented session/request with an http handler inside my DAL as follows...
Code:
public class SessionHandler : IHttpModule
{
private static readonly string KEY = "NHibernateSession";
public void Init(HttpApplication context)
{
context.EndRequest += new EventHandler(context_EndRequest);
}
public void Dispose()
{
}
private void context_EndRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
ISession session = context.Items[KEY] as ISession;
if (session != null)
{
try
{
session.Flush();
session.Close();
}
catch (Exception ex)
{
// log error.
throw ex;
}
}
context.Items[KEY] = null;
}
public static ISession CurrentSession
{
get
{
HttpContext currentContext = HttpContext.Current;
ISession session = currentContext.Items[KEY] as ISession;
if (session == null)
{
session = NHibernateUtil.GetSession();
currentContext.Items[KEY] = session;
}
return session;
}
}
}
In my DAL I have code like the following...
Code:
public virtual void Save(object obj)
{
ITransaction tx = null;
try
{
tx = session.BeginTransaction();
session.Save(obj);
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
throw ex;
}
}
The problem I have is that my DAL class rolls back the transaction by calling tx.Rollback() (which works fine) and then the http handler calls session.Flush() and session.Close() which seems to put the data back into the database.
I am guessing that session.Flush() is doing this? Has anyone else had this problem or know what I am doing wrong here?