| | | 1 | | using ILogger = Serilog.ILogger; |
| | | 2 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 3 | | |
| | | 4 | | namespace Syki.Back.Filters; |
| | | 5 | | |
| | | 6 | | public class DbContextTransactionFilter : TypeFilterAttribute |
| | | 7 | | { |
| | 40 | 8 | | public DbContextTransactionFilter() : base(typeof(DbContextTransactionFilterImpl)) { } |
| | | 9 | | |
| | 2122 | 10 | | private class DbContextTransactionFilterImpl(SykiDbContext sykiDbContext, ILogger logger) : IAsyncActionFilter |
| | | 11 | | { |
| | | 12 | | public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) |
| | | 13 | | { |
| | 2122 | 14 | | sykiDbContext.Database.AutoSavepointsEnabled = false; |
| | 2122 | 15 | | await using var transaction = await sykiDbContext.Database.BeginTransactionAsync(); |
| | | 16 | | |
| | | 17 | | try |
| | | 18 | | { |
| | 2122 | 19 | | var actionExecuted = await next(); |
| | 2122 | 20 | | if (actionExecuted.Result is BadRequestObjectResult || (actionExecuted.Exception != null && !actionExecu |
| | | 21 | | { |
| | 82 | 22 | | await transaction.RollbackAsync(); |
| | | 23 | | } |
| | | 24 | | else |
| | | 25 | | { |
| | 2040 | 26 | | await transaction.CommitAsync(); |
| | | 27 | | } |
| | 2122 | 28 | | } |
| | 0 | 29 | | catch (Exception) |
| | | 30 | | { |
| | | 31 | | try |
| | | 32 | | { |
| | 0 | 33 | | await transaction.RollbackAsync(); |
| | 0 | 34 | | } |
| | 0 | 35 | | catch (Exception ex) |
| | | 36 | | { |
| | 0 | 37 | | logger.Error("Rollback Error -> {Message}", ex.Message); |
| | 0 | 38 | | } |
| | | 39 | | |
| | 0 | 40 | | throw; |
| | | 41 | | } |
| | 2122 | 42 | | } |
| | | 43 | | } |
| | | 44 | | } |