diff --git a/src/SlimMessageBus.Host.Outbox.Sql.DbContext/DbContextTransactionService.cs b/src/SlimMessageBus.Host.Outbox.Sql.DbContext/DbContextTransactionService.cs index 5e5a8005..5bda0ecc 100644 --- a/src/SlimMessageBus.Host.Outbox.Sql.DbContext/DbContextTransactionService.cs +++ b/src/SlimMessageBus.Host.Outbox.Sql.DbContext/DbContextTransactionService.cs @@ -4,25 +4,31 @@ public class DbContextTransactionService(TDbContext dbContext, ISqlS : AbstractSqlTransactionService((SqlConnection)dbContext.Database.GetDbConnection()) where TDbContext : Microsoft.EntityFrameworkCore.DbContext { + private IDbContextTransaction _currentTransaction; + public TDbContext DbContext { get; } = dbContext; - public override SqlTransaction CurrentTransaction => (SqlTransaction)DbContext.Database.CurrentTransaction?.GetDbTransaction(); + public override SqlTransaction CurrentTransaction => _currentTransaction?.GetDbTransaction() as SqlTransaction; - protected override Task OnBeginTransaction() + protected override async Task OnBeginTransaction() { - return DbContext.Database.BeginTransactionAsync(sqlSettings.TransactionIsolationLevel); + _currentTransaction = await DbContext.Database.BeginTransactionAsync(sqlSettings.TransactionIsolationLevel); } - protected override Task OnCompleteTransaction(bool transactionFailed) + protected override async Task OnCompleteTransaction(bool transactionFailed) { - if (transactionFailed) - { - DbContext.Database.RollbackTransaction(); - } - else + if (_currentTransaction != null) { - DbContext.Database.CommitTransaction(); + if (transactionFailed) + { + await _currentTransaction.RollbackAsync(); + } + else + { + await _currentTransaction.CommitAsync(); + } + _currentTransaction.Dispose(); + _currentTransaction = null; } - return Task.CompletedTask; } } \ No newline at end of file