I'm following this example on how to implement session-per-request transactions in NHibernate.
I've got the following:
public class SessionManagementAttribute : ActionFilterAttribute
{
private ISessionFactory SessionFactory { get; set; }
public SessionManagementAttribute()
{
SessionFactory = WebApiApplication.SessionFactory;
}
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
var session = SessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
session.BeginTransaction();
}
public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
{
var session = SessionFactory.GetCurrentSession();
var transaction = session.Transaction;
if (transaction != null && transaction.IsActive)
{
// TODO: Do I need to rollback a transaction here?
transaction.Commit();
}
session = CurrentSessionContext.Unbind(SessionFactory);
session.Close();
}
}
I'm wondering -- if my transaction commit fails and an NHibernate exception is thrown -- should I be catching that and rolling back the transaction? In my current code I have an explicit catch and rollback. For example,
public void Save(Video video)
{
try
{
NHibernateSessionManager.Instance.BeginTransaction();
DoSave(video);
NHibernateSessionManager.Instance.CommitTransaction();
}
catch (Exception exception)
{
Logger.Error(exception);
NHibernateSessionManager.Instance.RollbackTransaction();
throw;
}
}
but I've seen hints through my readings that this might not be necessary. Can anyone clarify?