| | 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 | |
|
| 2028 | 10 | | private class DbContextTransactionFilterImpl(SykiDbContext sykiDbContext, ILogger logger) : IAsyncActionFilter |
| | 11 | | { |
| | 12 | | public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) |
| | 13 | | { |
| 2028 | 14 | | sykiDbContext.Database.AutoSavepointsEnabled = false; |
| 2028 | 15 | | await using var transaction = await sykiDbContext.Database.BeginTransactionAsync(); |
| | 16 | |
|
| | 17 | | try |
| | 18 | | { |
| 2028 | 19 | | var actionExecuted = await next(); |
| 2028 | 20 | | if (actionExecuted.Result is BadRequestObjectResult || (actionExecuted.Exception != null && !actionExecu |
| | 21 | | { |
| 64 | 22 | | await transaction.RollbackAsync(); |
| | 23 | | } |
| | 24 | | else |
| | 25 | | { |
| 1964 | 26 | | await transaction.CommitAsync(); |
| | 27 | | } |
| 2028 | 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 | | } |
| 2028 | 42 | | } |
| | 43 | | } |
| | 44 | | } |