views:

2145

answers:

5

Can anyone give me a quick overview of using TransactionScope with NHibernate? Do I need to do anything special with the session/IEnlistmentNotification/etc. to get this to work? Are there any pitfalls that I should worry about? For example, can I replace all of my hibernate transactions:

var transaction = session.BeginTransaction();
try
{
    // code
    transaction.Commit();
}
catch (Exception)
{
    transaction.Rollback();
}

with this?:

using (var scope = new TransactionScope())
{
    // code
    scope.Complete();
}
+4  A: 

I've testing this out using varying vendors and it just works. If you don't have "scope.Complete()" then the transaction will roll back. You must have MSDTC running the machine(s) involved. MSDTC will automatically detect the ambient ADO.NET transactions.

Adam Fyles
+3  A: 

The above works OK provided you are using a connection provider that supports the use of a Light-weight Transaction Manager, such as SQL Server 2005/2008.

If you are using SQL Server 7/2000 then all of your transactions will become Distributed Transactions even if you only hit one database/resource. This is probably not what you would want in most cases, and will be expensive performance wise.

So checkout if your connection provider and database server combination are suitable for use with TransactionScope.

+1  A: 

Also, if you are using TransactionScope, upgrade to NHibernate 2.1. It is only with 2.1 that NH really gotten good integration with TransactionScope.

Rohit Agarwal
@Rohit - can you provide any more detail with your answer?
Richard Ev
A: 

According to Fabio Maulo in comments related to NH-2107:

You can use TransactionScope and you should continue using NH's transaction too. Where you have read that the Usage of TransactionScope mean the avoid of usage of NH's transaction ?

I would have assumed that explicit usage of NHibernate's transactions not necessary, but aparently that's best practice

Andrew Smith