Just wondering, if I want to create a class that does something and I want to be able to be used in a TransactionScope, what would I need to implement?
That is: My class needs to be aware that it's in a Transaction, but how would it get notified on Commit or Rollback? And on Rollback, how would I actually Rollback?
I assume my class would have methods like "Add", "Update" and "Delete" which only modify a temporary list of changes, and a method "Read" which needs to detect if it is in a transaction and return modified or unmodified data accordingly, but then I need a method Commit/Rollback that gets called somehow?
Would I subscribe to the Transaction.TransactionCompleted event? If yes, how do I avoid multiple subscriptions to the same transaction?
I noticed that Transactions do not have IDs, is there a way to manage/juggle with multiple concurrent transactions or nested transactions?
The MSDN Documentation for System.Transactions has a lot of content but it seems to be aimed at consumers rather than implementors, so I wonder if someone has a good source (either on the web or in a book) on how a service would provide support for Transactions?
Let's assume that my Class does not have an underlying store that already supports transactions and is able to just "pass it through". Let's assume my class looks like this:
public class MyClass { private List<MyObject> _businessData; public void Create(Myobject data) { ... } public MyObject Read(string query) { ... } public void Update(Myobject data) { ... } public void Delete(Myobject data) { ... } }
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 transaction roughly translates to current active transaction. SOme context would help here. Lets take a look at sql transaction. using (IDbTransaction tran = conn.BeginTransaction()) { try { // your code tran.Commit(); } catch { tran.Rollback(); throw; } }
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.
This article has a good overview of what is required. It's older, but I believe it all still applies.
To summarize the article, you need to call one of the Enlist
methods on the Transaction class, passing in an implementation of IEnlistmentNotification
.
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