Mic*_*cah 7 .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);
}
Run Code Online (Sandbox Code Playgroud)
如果对数据库的任何更新失败,我需要将其他更新回滚并退出.我只是通过我可以调用的存储库公开Connection对象
Connection.BeginTransaction()
或者,我只是在服务层验证,只是在存储库中调用一个保存所有对象并处理事务的方法?这对我来说似乎并不合适.看起来它会迫使我在数据层中投入很多业务逻辑.
什么是正确的方法?如果我需要跨越存储库(或者那是不好的设计)怎么办?
我假设你在这里使用.NET.在这种情况下,您可以简单地将整个代码部分包装在一个带有实例的using语句中,TransactionScope它将为您处理事务语义.你只需要在最后调用Complete方法:
//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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果发生异常,则具有在Complete退出代码块时不调用的效果; 该Dispose方法对TransactionScope在实施IDisposable接口时的范围被称为using声明退出.
在Dispose调用中,它检查事务是否已完成(Complete成功时设置此状态).如果未设置该状态,则执行回滚.
然后,您可以将此嵌套在其他TransactionScope实例中(在同一线程上的调用堆栈中更深),以在多个存储库中创建更大的事务.