使用事务处理业务流程和存储库模式

时间:2009-03-24 19:36:29

标签: .net transactions repository-pattern

我有一种情况(我猜是非常标准的)我需要执行一些业务计算并在数据库中创建一堆记录。如果在任何时候出现任何问题,我需要从数据库中回滚所有内容。显然,我需要某种交易。我的问题是我在哪里实现事务支持。这是我的例子

//BillingServices - This is my billing service layer. called from the UI
public Result GenerateBill(BillData obj)
{
     //Validate BillData

     //Create a receivable line item in the receivables ledger 
     BillingRepository.Save(receivableItem);

     //Update account record to reflect new billing information
     BillingRepository.Save(accountRecord);

     //...do a some other stuff
     BillingRepository.Save(moreStuffInTheDatabase);
}

如果对数据库的任何更新失败,我需要回滚其他的更新并退出。我是否只通过我可以调用

的存储库公开Connection对象

Connection.BeginTransaction()

或者我是否只是在服务层验证,只需在存储库中调用一个保存所有对象并处理事务的方法?这对我来说似乎并不合适。看起来它会迫使我在数据层中投入很多业务逻辑。

什么是正确的方法?如果我需要跨越存储库(或者那会是糟糕的设计)会怎么样?

1 个答案:

答案 0 :(得分:5)

我假设你在这里使用.NET。既然如此,您只需将整个代码部分包装在using statement TransactionScope实例中,它就会为您处理事务语义。您只需在结尾处拨打Complete method

//BillingServices - This is my billing service layer. called from the UI
public Result GenerateBill(BillData obj)
{
     // Create the transaction scope, this defaults to Required.
     using (TransactionScope txScope = new TransactionScope())
     {
          //Validate BillData

          //Create a receivable line item in the receivables ledger 
          BillingRepository.Save(receivableItem);

          //Update account record to reflect new billing information
          BillingRepository.Save(accountRecord);

          //...do a some other stuff
          BillingRepository.Save(moreStuffInTheDatabase);

          // Commit the transaction.
          txScope.Complete();
     }
}

如果发生异常,则在退出代码块时不会调用Complete;退出TransactionScope语句的范围时,将调用Dispose method using实现上的IDisposable interface

Dispose调用中,它会检查事务是否已完成(当Complete成功时设置此状态)。如果未设置该状态,则执行回滚。

然后,您可以将其嵌套在其他TransactionScope实例中(在同一线程的调用堆栈中更深处),以在多个存储库中创建更大的事务。