Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use TransactionScope properly?

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?

like image 764
Denis Avatar asked Jan 04 '13 16:01

Denis


People also ask

What is the use of TransactionScope in C#?

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.

What is an ambient transaction?

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.

What is transaction scope in asp net?

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.


1 Answers

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.

like image 176
Trevor Pilley Avatar answered Sep 20 '22 15:09

Trevor Pilley