Skip to content
This repository has been archived by the owner on Oct 8, 2020. It is now read-only.

Transaction scopes

danielwertheim edited this page Nov 14, 2011 · 11 revisions

The unit of work normally makes use of plain ADO.Net transactions, but from v2.1 SisoDb now allows you to make use of the TransactionScope-class but only as long as the targeted storage does support transaction scopes.

using(var unitOfWork = dataBase.CreateUnitOfWork())
{
    unitOfWork.InsertMany(customers);
    unitOfWork.Commit();
}

This is all fine but suppose you want to control several UnitOfWorks, well the obvious solution is to use the TransactionScope class. If we are targetting, e.g SQL Server 2008, which does support transaction scopes and nested transactions we also don’t want to escalate to an distributed transaction, even if multiple connections are opened targeting the same DB using the same connection string. This is now supported. Hence you can do things like:

using(var ts = new TransactionScope())
{
    using(var unitOfWork = dataBase.CreateUnitOfWork())
    {
        unitOfWork.InsertMany(customers);
        unitOfWork.Commit();
    }

    ts.Complete();
}

The UnitOfWork will check if there is an ongoing Transaction from a TransactionScope, and if there is, no ADO.Net transactions will be created and the Commit and Rollback of the UnitOfWork is left to the outer TransactionScope.

You can of course have multiple UnitOfWorks as well:

using(var ts = new TransactionScope())
{
    using(var unitOfWork = dataBase.CreateUnitOfWork())
    {
        unitOfWork.InsertMany(customers1);
        unitOfWork.Commit();
    }

    using(var unitOfWork = dataBase.CreateUnitOfWork())
    {
        unitOfWork.InsertMany(customers2);
        unitOfWork.Commit();
    }

    ts.Complete();
}
Clone this wiki locally