问题
I am trying to add a middleware so that transaction begins at the beginning of the request and commits or rollbacks depending on the situation. This is my middleware:
public class TransactionPerRequestMiddleware
{
private readonly RequestDelegate next_;
public TransactionPerRequestMiddleware(RequestDelegate next)
{
next_ = next;
}
public async Task Invoke(HttpContext context, AppDbContext dbContext)
{
var is_everything_ok = true;
var transaction = dbContext.Database.BeginTransaction(
System.Data.IsolationLevel.ReadCommitted);
if (context.Response.StatusCode != 200 && is_everything_ok)
{
is_everything_ok = false;
}
await next_.Invoke(context);
if ((context.Response.StatusCode == 200 ||
context.Response.StatusCode == 302) && is_everything_ok)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
I registered the above middleware in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<TransactionPerRequestMiddleware>();
}
I have a method in service which performs two database operations one after another.
public void method()
{
databaseOperation1();
databaseOperation2();
}
If exception occurs in databaseOperation2() , databaseOperation1() is not rolling back currently. I am trying to implement Unit Of Work for each web request.
Thanks in advance.
来源:https://stackoverflow.com/questions/54035873/transaction-per-request-middleware-not-working