Transaction Per Request Middleware Not working

南楼画角 提交于 2019-12-12 01:19:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!