手工搭建基于ABP的框架 - 工作单元以及事务管理
在现代应用开发中,数据一致性是核心需求之一。当我们需要同时修改多个数据源(如订单表和库存表)时,必须确保这些操作要么全部成功,要么全部失败——这就是事务的核心价值。而**工作单元(Unit of Work,简称UoW)**则是封装事务逻辑、简化开发者复杂度的关键模式。
ABP(AspNet Boilerplate)作为一套成熟的.NET开发框架,内置了强大的UoW与事务管理机制。但很多开发者仅停留在“用注解”的层面,对其底层原理和手动扩展知之甚少。本文将带你从0到1手工搭建ABP风格的UoW与事务框架,深入理解其生命周期、传播行为,并掌握最佳实践。
目录#
- 工作单元(Unit of Work)基础
- 1.1 什么是工作单元?
- 1.2 ABP中的UoW核心概念
- 1.3 UoW的生命周期
- 事务管理的底层原理
- 2.1 数据库事务的ACID特性
- 2.2 ABP如何整合事务?
- 2.3 事务传播行为(Propagation)
- 手工搭建UoW与事务框架的步骤
- 3.1 环境准备
- 3.2 定义UoW接口与基础实现
- 3.3 整合数据库上下文(以EF Core为例)
- 3.4 实现事务管理逻辑
- 3.5 依赖注入配置
- 进阶使用与最佳实践
- 4.1 手动控制UoW的范围
- 4.2 多数据库事务(分布式事务)
- 4.3 避免常见陷阱
- 示例:完整的业务场景演示
- 总结与展望
- 参考资料
1. 工作单元(Unit of Work)基础#
1.1 什么是工作单元?#
工作单元是Martin Fowler提出的设计模式,核心目标是:
- 将多个数据操作(如新增、修改、删除)封装为一个“原子单元”;
- 跟踪所有对象的变更,确保它们要么一起提交(Commit),要么一起回滚(Rollback);
- 减少数据库连接的重复创建,提升性能。
简单来说,UoW是事务的“容器”——它帮你管理事务的生命周期,你只需要关注业务逻辑。
1.2 ABP中的UoW核心概念#
ABP对UoW进行了抽象,定义了以下核心组件:
| 组件 | 作用 |
|---|---|
IUnitOfWork | UoW的核心接口,定义BeginAsync/CommitAsync/RollbackAsync等方法 |
IUnitOfWorkManager | 管理UoW的生命周期(创建、获取当前UoW) |
UnitOfWorkAttribute | 注解式UoW,通过AOP自动创建/提交事务 |
UnitOfWorkOptions | 配置UoW的行为(如事务隔离级别、传播方式) |
关键区别:Ambient UoW vs 显式UoW#
- Ambient UoW(环境UoW):由框架自动管理(如Web请求上下文),所有嵌套调用共享同一个UoW;
- 显式UoW:通过
IUnitOfWorkManager.BeginAsync()手动创建,完全控制生命周期。
1.3 UoW的生命周期#
一个典型的UoW生命周期如下:
- 创建:通过
IUnitOfWorkManager或UnitOfWorkAttribute创建; - 初始化:绑定数据库上下文(DbContext),开启事务;
- 执行:跟踪业务逻辑中的数据变更(如
Add/Update); - 完成:调用
CommitAsync提交事务(或RollbackAsync回滚); - 销毁:释放数据库连接,清理资源。
示例流程:
graph TD
A[请求到达Controller] --> B[框架创建Ambient UoW]
B --> C[Service方法执行数据操作]
C --> D[UoW自动调用SaveChangesAsync]
D --> E{是否有异常?}
E -->|否| F[Commit事务]
E -->|是| G[Rollback事务]
F --> H[销毁UoW]
G --> H2. 事务管理的底层原理#
2.1 数据库事务的ACID特性#
事务必须满足ACID:
- 原子性(Atomicity):操作要么全成,要么全败;
- 一致性(Consistency):事务结束后数据状态合法;
- 隔离性(Isolation):多个事务并发时互不干扰;
- 持久性(Durability):事务提交后数据永久保存。
ABP的UoW本质是通过ORM(如EF Core)实现ACID,但封装了底层细节。
2.2 ABP如何整合事务?#
ABP的事务管理遵循以下逻辑:
- 绑定ORM上下文:UoW会关联一个或多个
DbContext(对应多个数据库); - 开启事务:调用
DbContext.Database.BeginTransactionAsync(); - 跟踪变更:
DbContext自动跟踪实体的状态(新增/修改/删除); - 提交事务:先调用
DbContext.SaveChangesAsync()(将变更写入数据库),再调用Transaction.CommitAsync(); - 回滚事务:若任何步骤失败,调用
Transaction.RollbackAsync()。
关键细节:UoW会确保所有DbContext的事务同步提交/回滚——即使操作跨多个数据库,也能保证原子性(需分布式事务支持)。
2.3 事务传播行为(Propagation)#
传播行为定义了子事务与父事务的关系,ABP支持以下6种:
| 行为 | 含义 |
|---|---|
Required(默认) | 若有父事务则加入,否则创建新事务 |
RequiresNew | 强制创建新事务,与父事务完全隔离 |
Supports | 若有父事务则加入,否则不使用事务 |
NotSupported | 不使用事务,若有父事务则暂停 |
Mandatory | 必须有父事务,否则抛出异常 |
Never | 不能有父事务,否则抛出异常 |
示例场景:
- 日志记录:用
RequiresNew——即使主事务回滚,日志仍需保存; - 查询操作:用
Supports——不需要事务,提升性能; - 核心业务:用
Required——确保原子性。
3. 手工搭建UoW与事务框架的步骤#
接下来,我们将从0到1实现ABP风格的UoW框架,以EF Core为例。
3.1 环境准备#
- .NET 8 SDK
- ABP Core包:
Volo.Abp.Core - EF Core包:
Microsoft.EntityFrameworkCore、Microsoft.EntityFrameworkCore.SqlServer
3.2 定义UoW接口与基础实现#
首先,定义IUnitOfWork接口:
public interface IUnitOfWork : IDisposable, IAsyncDisposable
{
Guid Id { get; }
bool IsActive { get; }
Task BeginAsync(CancellationToken cancellationToken = default);
Task CommitAsync(CancellationToken cancellationToken = default);
Task RollbackAsync(CancellationToken cancellationToken = default);
void AddDbContext<TContext>(TContext context) where TContext : DbContext;
TContext GetDbContext<TContext>() where TContext : DbContext;
IEnumerable<DbContext> GetAllDbContexts();
}然后,实现基础类UnitOfWorkBase(核心逻辑):
public abstract class UnitOfWorkBase : IUnitOfWork
{
public Guid Id { get; } = Guid.NewGuid();
public bool IsActive { get; private set; }
private readonly Dictionary<Type, DbContext> _dbContexts = new();
private readonly List<DbContextTransaction> _transactions = new();
// 实现接口方法...
public async Task BeginAsync(CancellationToken cancellationToken = default)
{
if (IsActive) throw new InvalidOperationException("UoW已激活");
// 为每个DbContext开启事务
foreach (var context in _dbContexts.Values)
{
var transaction = await context.Database.BeginTransactionAsync(cancellationToken);
_transactions.Add(transaction);
}
IsActive = true;
}
public async Task CommitAsync(CancellationToken cancellationToken = default)
{
if (!IsActive) throw new InvalidOperationException("UoW未激活");
try
{
// 先保存所有DbContext的变更
foreach (var context in _dbContexts.Values)
{
await context.SaveChangesAsync(cancellationToken);
}
// 再提交所有事务
foreach (var transaction in _transactions)
{
await transaction.CommitAsync(cancellationToken);
}
IsActive = false;
}
catch
{
await RollbackAsync(cancellationToken);
throw;
}
}
// 其他方法(Rollback/Dispose)...
}3.3 整合数据库上下文(以EF Core为例)#
UoW需要管理DbContext,因此需要一个上下文提供器:
public interface IDbContextProvider<TContext> where TContext : DbContext
{
Task<TContext> GetDbContextAsync(CancellationToken cancellationToken = default);
}
public class DbContextProvider<TContext> : IDbContextProvider<TContext> where TContext : DbContext
{
private readonly IServiceProvider _serviceProvider;
public DbContextProvider(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task<TContext> GetDbContextAsync(CancellationToken cancellationToken = default)
{
// 通过Scope创建DbContext,避免跨请求共享
using var scope = _serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<TContext>();
await context.Database.EnsureCreatedAsync(cancellationToken);
return context;
}
}然后,实现EF Core-specific的UoW:
public class EfCoreUnitOfWork : UnitOfWorkBase
{
private readonly IServiceProvider _serviceProvider;
public EfCoreUnitOfWork(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public override async Task BeginAsync(CancellationToken cancellationToken = default)
{
// 自动添加所有注册的DbContext
var orderContext = await _serviceProvider.GetRequiredService<IDbContextProvider<OrderDbContext>>().GetDbContextAsync(cancellationToken);
var inventoryContext = await _serviceProvider.GetRequiredService<IDbContextProvider<InventoryDbContext>>().GetDbContextAsync(cancellationToken);
AddDbContext(orderContext);
AddDbContext(inventoryContext);
await base.BeginAsync(cancellationToken);
}
}3.4 实现事务管理逻辑#
ABP的IUnitOfWorkManager负责创建和跟踪UoW,实现如下:
public interface IUnitOfWorkManager
{
IUnitOfWork Current { get; }
Task<IUnitOfWork> BeginAsync(UnitOfWorkOptions options = null, CancellationToken cancellationToken = default);
}
public class UnitOfWorkManager : IUnitOfWorkManager
{
private readonly IServiceProvider _serviceProvider;
private readonly AsyncLocal<IUnitOfWork> _currentUoW = new(); // 跨Async/Await保存当前UoW
public IUnitOfWork Current => _currentUoW.Value;
public UnitOfWorkManager(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task<IUnitOfWork> BeginAsync(UnitOfWorkOptions options = null, CancellationToken cancellationToken = default)
{
options ??= new UnitOfWorkOptions();
var uow = _serviceProvider.GetRequiredService<IUnitOfWork>();
// 配置隔离级别
if (options.IsolationLevel.HasValue)
{
foreach (var context in uow.GetAllDbContexts())
{
context.Database.SetTransactionIsolationLevel(options.IsolationLevel.Value);
}
}
await uow.BeginAsync(cancellationToken);
_currentUoW.Value = uow;
return uow;
}
}3.5 依赖注入配置#
在ABP模块中注册所有组件:
public class MyAbpModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
var services = context.Services;
var config = context.Configuration;
// 1. 注册DbContext
services.AddDbContext<OrderDbContext>(opt => opt.UseSqlServer(config.GetConnectionString("OrderDb")));
services.AddDbContext<InventoryDbContext>(opt => opt.UseSqlServer(config.GetConnectionString("InventoryDb")));
// 2. 注册DbContextProvider
services.AddTransient(typeof(IDbContextProvider<>), typeof(DbContextProvider<>));
// 3. 注册UoW
services.AddTransient<IUnitOfWork, EfCoreUnitOfWork>();
services.AddTransient<IUnitOfWorkManager, UnitOfWorkManager>();
// 4. 注册UoW中间件(Web应用)
services.AddTransient<UnitOfWorkMiddleware>();
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
app.UseMiddleware<UnitOfWorkMiddleware>(); // 自动创建Ambient UoW
}
}4. 进阶使用与最佳实践#
4.1 手动控制UoW的范围#
注解式UoW(UnitOfWorkAttribute)适合简单场景,复杂场景需手动控制:
public class OrderService
{
private readonly IUnitOfWorkManager _uowManager;
private readonly IOrderRepository _orderRepo;
private readonly IInventoryRepository _inventoryRepo;
public OrderService(IUnitOfWorkManager uowManager, IOrderRepository orderRepo, IInventoryRepository inventoryRepo)
{
_uowManager = uowManager;
_orderRepo = orderRepo;
_inventoryRepo = inventoryRepo;
}
public async Task CreateOrderAsync(CreateOrderDto input, CancellationToken cancellationToken = default)
{
// 手动开启UoW(隔离级别:Serializable)
using var uow = await _uowManager.BeginAsync(new UnitOfWorkOptions
{
IsolationLevel = IsolationLevel.Serializable
}, cancellationToken);
try
{
// 1. 创建订单
var order = new Order(input.ProductId, input.Quantity, input.TotalAmount);
await _orderRepo.InsertAsync(order, cancellationToken);
// 2. 扣减库存
var inventory = await _inventoryRepo.GetByProductIdAsync(input.ProductId, cancellationToken);
if (inventory == null) throw new BusinessException("库存不存在");
inventory.ReduceStock(input.Quantity);
await _inventoryRepo.UpdateAsync(inventory, cancellationToken);
// 提交事务
await uow.CommitAsync(cancellationToken);
}
catch (Exception ex)
{
await uow.RollbackAsync(cancellationToken);
throw new BusinessException("创建订单失败", ex);
}
}
}4.2 多数据库事务(分布式事务)#
若操作跨多个数据库(如OrderDb和InventoryDb),需使用分布式事务。ABP支持两种方案:
- 2PC(两阶段提交):通过
DotNetTransactionManager或DTM实现; - Outbox Pattern:异步化事务(适合高并发场景)。
示例(DTM):
public async Task CreateOrderAsync(CreateOrderDto input)
{
var dtmClient = _serviceProvider.GetRequiredService<DtmClient>();
var gid = await dtmClient.GenGidAsync();
// 开启分布式事务
await dtmClient.TccGlobalTransactionAsync(gid, async (tcc) =>
{
// 1. 调用订单服务的Try方法
await tcc.CallBranchAsync(
new CreateOrderRequest(input),
"http://order-service/api/orders/try",
"http://order-service/api/orders/confirm",
"http://order-service/api/orders/cancel"
);
// 2. 调用库存服务的Try方法
await tcc.CallBranchAsync(
new ReduceInventoryRequest(input.ProductId, input.Quantity),
"http://inventory-service/api/inventory/try",
"http://inventory-service/api/inventory/confirm",
"http://inventory-service/api/inventory/cancel"
);
});
}4.3 避免常见陷阱#
-
不要在UoW中包含耗时操作:
- 错误:UoW包含调用外部API(如支付);
- 正确:拆分UoW,仅包含数据库操作。
// 错误示例 [UnitOfWork] public async Task ProcessOrderAsync(Order order) { await _orderRepo.InsertAsync(order); await _paymentService.ChargeAsync(order); // 耗时操作,可能锁表 order.MarkAsPaid(); await _orderRepo.UpdateAsync(order); } // 正确示例 public async Task ProcessOrderAsync(Order order) { // 阶段1:保存订单(短UoW) using var uow1 = await _uowManager.BeginAsync(); await _orderRepo.InsertAsync(order); await uow1.CommitAsync(); // 阶段2:调用支付API(无UoW) await _paymentService.ChargeAsync(order); // 阶段3:更新订单状态(短UoW) using var uow2 = await _uowManager.BeginAsync(); order.MarkAsPaid(); await _orderRepo.UpdateAsync(order); await uow2.CommitAsync(); } -
不要在多线程中使用Ambient UoW:
AsyncLocal仅在当前线程有效,多线程需手动创建UoW。
-
仓库必须从UoW获取DbContext:
- 错误:仓库直接依赖
DbContext; - 正确:仓库依赖
IUnitOfWork,通过GetDbContext<T>()获取。
// 正确的仓库实现 public class OrderRepository : IOrderRepository { private readonly IUnitOfWork _uow; public OrderRepository(IUnitOfWork uow) { _uow = uow; } public async Task InsertAsync(Order order, CancellationToken cancellationToken = default) { var dbContext = _uow.GetDbContext<OrderDbContext>(); await dbContext.Orders.AddAsync(order, cancellationToken); } } - 错误:仓库直接依赖
5. 示例:完整的业务场景演示#
我们以“创建订单并扣减库存”为例,演示UoW的完整流程:
5.1 业务需求#
- 用户提交订单,系统创建订单记录;
- 扣减对应商品的库存;
- 若库存不足,回滚所有操作。
5.2 代码实现#
1. 实体定义#
// 订单实体
public class Order
{
public Guid Id { get; private set; }
public Guid ProductId { get; private set; }
public int Quantity { get; private set; }
public decimal TotalAmount { get; private set; }
public OrderStatus Status { get; private set; }
public Order(Guid productId, int quantity, decimal totalAmount)
{
Id = Guid.NewGuid();
ProductId = productId;
Quantity = quantity;
TotalAmount = totalAmount;
Status = OrderStatus.Created;
}
public void MarkAsPaid() => Status = OrderStatus.Paid;
}
// 库存实体
public class Inventory
{
public Guid ProductId { get; private set; }
public int StockQuantity { get; private set; }
public Inventory(Guid productId, int stockQuantity)
{
ProductId = productId;
StockQuantity = stockQuantity;
}
public void ReduceStock(int quantity)
{
if (StockQuantity < quantity) throw new BusinessException("库存不足");
StockQuantity -= quantity;
}
}2. 服务实现#
public class OrderService
{
private readonly IUnitOfWorkManager _uowManager;
private readonly IOrderRepository _orderRepo;
private readonly IInventoryRepository _inventoryRepo;
public OrderService(IUnitOfWorkManager uowManager, IOrderRepository orderRepo, IInventoryRepository inventoryRepo)
{
_uowManager = uowManager;
_orderRepo = orderRepo;
_inventoryRepo = inventoryRepo;
}
[UnitOfWork(IsolationLevel = IsolationLevel.Serializable)]
public async Task CreateOrderAsync(CreateOrderDto input, CancellationToken cancellationToken = default)
{
// 1. 创建订单
var order = new Order(input.ProductId, input.Quantity, input.TotalAmount);
await _orderRepo.InsertAsync(order, cancellationToken);
// 2. 扣减库存
var inventory = await _inventoryRepo.GetByProductIdAsync(input.ProductId, cancellationToken);
if (inventory == null) throw new BusinessException("库存不存在");
inventory.ReduceStock(input.Quantity);
await _inventoryRepo.UpdateAsync(inventory, cancellationToken);
// 3. 自动提交事务(由UnitOfWorkAttribute处理)
}
}3. 控制器调用#
[ApiController]
[Route("api/orders")]
public class OrdersController : AbpControllerBase
{
private readonly OrderService _orderService;
public OrdersController(OrderService orderService)
{
_orderService = orderService;
}
[HttpPost]
public async Task<IActionResult> CreateOrderAsync(CreateOrderDto input, CancellationToken cancellationToken = default)
{
await _orderService.CreateOrderAsync(input, cancellationToken);
return Ok("订单创建成功");
}
}5.3 测试场景#
- 正常流程:库存充足→订单创建成功,库存扣减;
- 异常流程:库存不足→
ReduceStock抛出异常→UoW自动回滚→订单未创建,库存未扣减。
6. 总结与展望#
通过本文的手工搭建,你应该掌握了:
- UoW的核心原理与ABP的抽象方式;
- 事务传播行为的实际应用;
- 多数据库与分布式事务的处理。
未来展望:
- 探索ABP的
IRepository接口与UoW的整合; - 学习
Caching与UoW的协同(如缓存失效); - 深入分布式事务的实现细节(如
DTM、Saga)。
7. 参考资料#
-
ABP官方文档:Unit of Work
-
EF Core事务文档:Transactions
-
Martin Fowler的UoW模式:Unit of Work
-
DTM分布式事务:DTM Docs
-
ABP事务管理:Transaction Management
码字不易,若有帮助请点赞收藏! 😊