在 ASP.NET Core Web API 中隐藏 DbContext 事务的一种解决方法是使用中间件来管理事务。
首先,创建一个名为 TransactionMiddleware
的中间件类:
public class TransactionMiddleware
{
private readonly RequestDelegate _next;
private readonly DbContext _dbContext;
public TransactionMiddleware(RequestDelegate next, DbContext dbContext)
{
_next = next;
_dbContext = dbContext;
}
public async Task Invoke(HttpContext context)
{
using (var transaction = _dbContext.Database.BeginTransaction())
{
try
{
await _next(context);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
}
然后,在 Startup.cs
文件的 ConfigureServices
方法中注册 DbContext 和中间件:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient();
services.AddControllers();
}
接下来,在 Configure
方法中使用中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, TransactionMiddleware transactionMiddleware)
{
// ...
app.UseMiddleware();
// ...
}
现在,当请求到达您的 Web API 控制器时,DbContext 事务会自动创建和管理。您可以在控制器中使用 DbContext,而不必担心事务的创建和提交/回滚。
请注意,此示例在每个请求上创建了一个新的 DbContext 实例。如果您希望在整个请求处理期间重用 DbContext 实例,可以根据需要进行修改。