I always want to try to use TransactionScope
but I just can't figure out what people see about it that is useful. So let's take an example:
using(TransactionScope tran = new TransactionScope()) { CallAMethodThatDoesSomeWork1(); CallAMethodThatDoesSomeWork2(); tran.Complete(); }
So the most basic question: How do I write "CallAMethodThatDoesSomeWork1()
" so that it knows how to roll its actions back if let's say "CallAMethodThatDoesSomeWork2()
" throws an exception?
The TransactionScope class provides a simple way to mark a block of code as participating in a transaction, without requiring you to interact with the transaction itself. A transaction scope can select and manage the ambient transaction automatically.
Ambient TransactionA transaction which automatically identifies a code block that needs to support a transaction without explicitly mentioning any transaction related things. An ambient transaction is not tied just to a database, any transaction aware provider can be used.
TransactionScope is a class of System Namespace. It can also be termed as Transactions Namespace. The TransactionScope class supports transactions from code blocks and that is why it plays a key role in the . NET development framework. This class usually manages local as well as distributed transactions from our code.
The code within the methods you call need to be transaction aware and enlist in the active transaction. This means creating or using classes which are resource managers (see Implement Your Own Resource Manager.
You do this by implementing IEnlistmentNotification and enlisting in the transaction. When the transaction is completed, the transaction manager will call methods as defined on that interface so that your code can do/undo the work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With