TransactionScope is a .NET class used to mark a block of code as transactional. It uses an implicit programming model so transactions are managed by the infrastructure, rather than the developer. The class was introduced in .NET 2.0.
Description
The TransactionScope class is part of the System.Transactions namespace. Unlike the System.Transactions.Transaction
class, which uses an explicit programming model, the TransactionScope
class uses an implicit programming model, which simplifies how transactions are used in client code.
How to use it
To use TransactionScope
, the developer simply creates a scope, does the transactional work and then indicates when the transaction is complete. There is no need to explicitly rollback the transaction in the case of an error.
using(var scope = new TransactionScope())
{
// do database or other transactional work here
scope.Complete();
}
Inside the scope, resources are automatically enlisted in the ambient transaction so there is no need to manage the transaction directly. The transaction is automatically rolled back unless it is marked as complete before TransactionScope
is disposed.
References