Skip to content

Instantly share code, notes, and snippets.

@rmueller
Created June 4, 2010 20:35
Show Gist options
  • Save rmueller/425905 to your computer and use it in GitHub Desktop.
Save rmueller/425905 to your computer and use it in GitHub Desktop.
using System.Web.Mvc;
using SharpArch.Data.NHibernate;
using System;
using NHibernate;
namespace SharpArch.Web.NHibernate
{
public class TransactionAttribute : ActionFilterAttribute
{
/// <summary>
/// When used, assumes the <see cref="factoryKey" /> to be NHibernateSession.DefaultFactoryKey
/// </summary>
public TransactionAttribute() { }
public bool RollbackOnModelStateError { get; set; }
/// <summary>
/// Overrides the default <see cref="factoryKey" /> with a specific factory key
/// </summary>
public TransactionAttribute(string factoryKey) {
this.factoryKey = factoryKey;
}
public override void OnActionExecuting(ActionExecutingContext filterContext) {
NHibernateSession.CurrentFor(GetEffectiveFactoryKey()).BeginTransaction();
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
string effectiveFactoryKey = GetEffectiveFactoryKey();
ITransaction currentTransaction =
NHibernateSession.CurrentFor(effectiveFactoryKey).Transaction;
filterContext.Controller.ViewData.ModelState.IsValid
if (currentTransaction.IsActive) {
if ((filterContext.Exception != null) && (filterContext.ExceptionHandled))
{
currentTransaction.Rollback();
}
}
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
string effectiveFactoryKey = GetEffectiveFactoryKey();
ITransaction currentTransaction =
NHibernateSession.CurrentFor(effectiveFactoryKey).Transaction;
base.OnResultExecuted(filterContext);
try
{
if (currentTransaction.IsActive) {
if ((filterContext.Exception != null) && (!filterContext.ExceptionHandled))
{
currentTransaction.Rollback();
}
else
{
currentTransaction.Commit();
}
}
}
finally
{
currentTransaction.Dispose();
}
}
private string GetEffectiveFactoryKey() {
return String.IsNullOrEmpty(factoryKey)
? NHibernateSession.DefaultFactoryKey
: factoryKey;
}
/// <summary>
/// Optionally holds the factory key to be used when beginning/committing a transaction
/// </summary>
private string factoryKey;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment