sinclairchase
sinclairchase

Reputation: 243

How do I rollback a transaction using Unit of Work and Repository patterns?

I have a user repository, which does all the user data access. I also have a unit of work class that manages the connection and transaction for my repositories. How do I effectively rollback a transaction on my unit of work class, if an error happens within my repository?

Create method on my UserRepository. I'm using Dapper for DataAccess.

try
{
    this.Connection.Execute("User_Create", parameters, this.Transaction, 
        commandType: CommandType.StoredProcedure);
}
catch (Exception)
{
    //Need to tell my unit of work to rollback the transaction.                
}

I pass both the connection and transaction that were created in my unit of work constructor to my repositories. Below is a property on my unit of work class.

public UserRepository UserRepository
{
    get
    {
        if (this._userRepository == null)
            this._userRepository = 
                new UserRepository(this._connection, this._transaction);
        return this._userRepository;
    }
}

I'm hoping to figure out the best approach.

* Update * After doing more research into the unit of work pattern I think I am using it completely wrong in my example.

Upvotes: 3

Views: 5375

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160982

Dapper supports TransactionScope, which provides a Complete() method to commit the transaction, if you don't call Complete() the transaction is aborted.

using (TransactionScope scope = new TransactionScope())
{
   //open connection, do your thing
   scope.Complete();
}

Upvotes: 5

Related Questions