Tuesday, June 12, 2007

.NET 2.0 transaction model

Currently .net provides 3 transaction models.

1. Using ADO.NET data providers.
2. Using enterprise services transaction.
3. Using System.Transactions for .NET Framework 2.0

The first 2 models have some shortcoming that we are going to discuss now.

1. The ADO.NET transaction model

In the transaction model we can not update more than one database in single transaction.

Lets have an example:

SqlConnection con = new SqlConnection("Connection String");
SqlTransaction tr = con.BeginTransaction();
SqlCommand cmd = new SqlCommand("Update query", con, tr);
catch (Exception exc)

In the code above, the transaction object is actually created from a connection to a single database. So there is no direct way of grouping updates to more than one database into a single transaction.

2. Enterprise services transactions

Though this model remove the shortcoming of the previous model as it provides distributed transaction manager that enable you to have transactions independent of the database but it also has some shortcomings:

* Class needs to inherit from the ServicedComponent class to implement enterprise service transactions that restrict your class from inheriting from any other base class.
* It takes transaction as a distributed transaction. Even if single database is involved, enterprise services will still take it as a distributed transaction and handle it as such. As a result, it using more resources than needed.
* The assembly you create need to be deployed in component services to run under the COM+ context.For that assembly must be strong named and registered using regsvcs.exe utility.

3. Introducing System.Transactions

The System.Transactions model is a new addition to the .NET 2.0 framework. It addresses the shortcomings in the

above discussed models, and brings the best features of the ADO.NET and enterprise services transaction models

In System.Transactions, you have the TransactionScope object you can use to scope a set of statements and group

them under one transaction.
Example -

C# Code
class AccountManager
void TransferCash(Account from, Account to, double amt)
using(TransactionScope scope=new TransactionScope())

As you can see in the code above, class needs not to inherit from any other class. System.Transactions is smart

enough to decide whether to use a distributed transaction or not. In case of single database is involved, it

uses lightweight transaction and if there are multiple databases involved, it will use a distributed


Reference: http://www.simple-talk.com/dotnet/.net-framework/.net-2.0-transaction-model/

No comments: