Created
September 30, 2016 07:40
-
-
Save geirsagberg/e56be49aea083f7a80bb23c89ce59b2c to your computer and use it in GitHub Desktop.
TransactionFactory for ambient transactions
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 TransactionFactory : ITransactionFactory | |
| { | |
| public ITransaction BeginTransaction(TransactionScopeOption option = TransactionScopeOption.Required, IsolationLevel isolationLevel = IsolationLevel.Unspecified) | |
| { | |
| var currentTransaction = System.Transactions.Transaction.Current; | |
| if (currentTransaction != null && option == TransactionScopeOption.Required) | |
| { | |
| if (isolationLevel == IsolationLevel.Unspecified || currentTransaction.IsolationLevel == isolationLevel) | |
| isolationLevel = currentTransaction.IsolationLevel; | |
| else | |
| throw new TransactionException( | |
| $"Kan ikke starte ny transaksjon med isolationlevel {isolationLevel} fordi den er nøstet inn i en eksisterende transaksjon med annet isolationlevel {currentTransaction.IsolationLevel}"); | |
| } | |
| else | |
| if(isolationLevel == IsolationLevel.Unspecified) | |
| isolationLevel = IsolationLevel.ReadCommitted; | |
| return new Transaction(option, isolationLevel); | |
| } | |
| /// <summary> | |
| /// Wrapper rundt TransactionScope for å kunne mocke transactions. | |
| /// </summary> | |
| public class Transaction : ITransaction | |
| { | |
| private readonly TransactionScope transactionScope; | |
| public Transaction(TransactionScopeOption scopeOption, IsolationLevel isolationLevel) | |
| { | |
| var transactionOptions = new TransactionOptions { | |
| IsolationLevel = isolationLevel, | |
| Timeout = TransactionManager.MaximumTimeout | |
| }; | |
| transactionScope = new TransactionScope(scopeOption, transactionOptions, TransactionScopeAsyncFlowOption.Enabled); | |
| } | |
| public void Dispose() | |
| { | |
| transactionScope.Dispose(); | |
| } | |
| public void Complete() | |
| { | |
| transactionScope.Complete(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment