The advantages of TransactionScope
are:
- you don't have to pass a transaction around (ADO.NET should enlist automatically)
- which means that you can even use a
TransactionScope
to add transactions to existing, closed-source code (i.e. no changes are required)
- a
TransactionScope
can (via DTC) span multiple resources (i.e. multiple databases, or a database and an MSMQ server, etc)
But you pay for this a little bit with speed. A connection-based transaction is slightly quicker (not much), but can only span a single resource and needs to be attached manually to all your DAL code. However, if you only talk to a single SQL2005/SQL2008 instance, then it can use the "LTM" - meaning it doesn't have to involve DTC (which is where most of the performance cost comes from) unless it absolutely needs to. Many TransactionScope
operations can therefore complete talking only to the database.
If you want to span 20 operations, then TransactionScope
should be ideal - it'll save you having to pass the transactions around, and allow each operation to manage their connection locally - making for highly re-usable code. Indeed, TransactionScope
can be nested in the ways you expect, so you can have:
void Deposit(...) { /* uses TranScope to do a deposit */ }
void Debit(...) { /* uses TranScope to do a debit */ }
void Transfer(...) { /* uses a TranScope to span Debit/Deposit */ }
To do this using database transactions you'd need to pass the connection and transaction objects to each method, which quickly gets ungainly - especially if you need to code to work with/without an existing open transaction (lots of "if(tran==null)
" etc).
For more information, see Transactions in .net