Created
February 18, 2014 20:42
-
-
Save tommarien/9079661 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Castle.DynamicProxy; | |
using NHibernate; | |
using IInterceptor = Castle.DynamicProxy.IInterceptor; | |
namespace Nebula.Bootstrapper.Interceptors | |
{ | |
public class AutoTxInterceptor : IInterceptor | |
{ | |
private readonly Lazy<ISession> session; | |
public AutoTxInterceptor(Lazy<ISession> session) | |
{ | |
this.session = session; | |
} | |
private IInvocation Owner { get; set; } | |
public void Intercept(IInvocation invocation) | |
{ | |
BeginTransactionIfNeeded(invocation); | |
try | |
{ | |
invocation.Proceed(); | |
CommitTransactionIfNeeded(invocation); | |
} | |
catch (Exception) | |
{ | |
RollBackTransactionIfNeeded(invocation); | |
throw; | |
} | |
} | |
private bool IsTransactionOwner(IInvocation invocation) | |
{ | |
return (Owner == invocation); | |
} | |
private void BeginTransactionIfNeeded(IInvocation invocation) | |
{ | |
if (session.Value.Transaction.IsActive) return; | |
session.Value.BeginTransaction(); | |
Owner = invocation; | |
} | |
private void CommitTransactionIfNeeded(IInvocation invocation) | |
{ | |
if (!IsTransactionOwner(invocation)) return; | |
session.Value.Transaction.Commit(); | |
Owner = null; | |
} | |
private void RollBackTransactionIfNeeded(IInvocation invocation) | |
{ | |
if (!IsTransactionOwner(invocation)) return; | |
session.Value.Transaction.Rollback(); | |
Owner = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment