Created
June 12, 2014 03:13
-
-
Save copypastedeveloper/0ccab60a152369c2047c to your computer and use it in GitHub Desktop.
example of how to make just about anything transaction aware
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
| 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