How to create a class that works with TransactionScope?

Michael Stum picture Michael Stum · Mar 10, 2011 · Viewed 8.2k times · Source

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) { ... }
}

Answer

Peter T. LaComb Jr. picture Peter T. LaComb Jr. · Mar 10, 2011

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.