如何使用工作单元和存储库模式回滚事务?

sin*_*ase 3 c# ado.net transactions repository unit-of-work

我有一个用户存储库,它可以访问所有用户数据.我还有一个工作类单元,用于管理我的存储库的连接和事务.如果我的存储库中发生错误,如何在我的工作单元上有效地回滚事务?

在我的UserRepository上创建方法.我正在使用Dapper进行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.                
}
Run Code Online (Sandbox Code Playgroud)

我将在我的工作单元构造函数中创建的连接和事务传递给我的存储库.以下是我工作单位的财产.

public UserRepository UserRepository
{
    get
    {
        if (this._userRepository == null)
            this._userRepository = 
                new UserRepository(this._connection, this._transaction);
        return this._userRepository;
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望找到最好的方法.

*更新* 在对工作单元模式进行更多研究后,我认为我在我的例子中使用它完全错误.

Bro*_*ass 5

Dapper支持TransactionScope,它提供了Complete()一种提交事务的方法,如果你没有调用Complete()事务中止.

using (TransactionScope scope = new TransactionScope())
{
   //open connection, do your thing
   scope.Complete();
}
Run Code Online (Sandbox Code Playgroud)