Reputation: 1637
Hi I'm using TransactionScope on several places in my app. Like:
using (var scope = new TransactionScope())
{
ToDo1();
ToDo2();
scope.Complete();
}
I would like to have a possibility to disable all my TransactionScopes in one place.
I imagining something like MyTransactionScope class, where I can define if I want to use it or not.
Can you give me a hint how to achieve it?
Thank you.
Upvotes: 3
Views: 2256
Reputation: 2554
I've done this. You can't inherit TransactionScope
because it is sealed. Instead you contain the class inside your MyTransactionScope
class. Also implement IDisposable
so you can call it under using construct. And expose .Complete()
and other related methods. These methods will internally call the inner contained object.
public sealed class MyTransactionScope : IDisposable
{
TransactionScope _transactionScope = null;
#region Overloaded Constructors
public MyTransactionScope()
{
_transactionScope = new TransactionScope();
}
public MyTransactionScope(Transaction transactionToUse)
{
_transactionScope = new TransactionScope(transactionToUse);
}
#endregion
public void Complete()
{
_transactionScope.Complete();
}
public void Dispose()
{
_transactionScope.Dispose();
}
}
Upvotes: 7
Reputation: 60559
If you mean what I think you mean, then you should be able to use the Suppress
transaction scope option:
using (var scope = new TransactionScope())
{
using(TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress)) {
ToDo1();
scope2.Complete();
}
// If ToDo2 throws an exception and the transaction is rolled back,
// ToDo1 will still be committed since it did not participate in the
// original (ambient) transaction.
ToDo2();
scope.Complete();
}
Upvotes: 2