Skip to content

Instantly share code, notes, and snippets.

@copypastedeveloper
Created June 12, 2014 03:13
Show Gist options
  • Select an option

  • Save copypastedeveloper/0ccab60a152369c2047c to your computer and use it in GitHub Desktop.

Select an option

Save copypastedeveloper/0ccab60a152369c2047c to your computer and use it in GitHub Desktop.
example of how to make just about anything transaction aware
public class TransactionalInvoker : IEnlistmentNotification
{
bool _inTransaction;
readonly List<Action> _commitActions = new List<Action>();
public void Invoke(Action action)
{
if (_inTransaction)
{
_commitActions.Add(action);
return;
}
if (Transaction.Current != null)
{
Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None);
_inTransaction = true;
_commitActions.Add(action);
return;
}
action.Invoke();
}
public void Prepare(PreparingEnlistment preparingEnlistment)
{
preparingEnlistment.Prepared();
}
public void Commit(Enlistment enlistment)
{
try
{
_commitActions.ForEach(x => x.Invoke());
_commitActions.Clear();
enlistment.Done();
}
catch (Exception ex)
{
Transaction currentTx = Transaction.Current;
if (currentTx != null)
{
currentTx.Rollback(ex);
}
}
finally
{
_inTransaction = false;
_commitActions.Clear();
}
}
public void Rollback(Enlistment enlistment)
{
_inTransaction = false;
_commitActions.Clear();
enlistment.Done();
}
public void InDoubt(Enlistment enlistment)
{
enlistment.Done();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment