34

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?

Jeff B
  • 8,572
  • 17
  • 61
  • 140
Denis
  • 11,796
  • 16
  • 88
  • 150

1 Answers1

23

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.

Trevor Pilley
  • 16,156
  • 5
  • 44
  • 60
  • 1
    Oh, I see how to do it. Wish the MSDN page for "TransactionScope" said it -- been looking at it and completely never saw the point of TransactionScope. This is the magic interface to make it work. This makes sense! – Denis Jan 04 '13 at 16:42