From a9238c9e09811dbd688d112e1cbda9efc426399e Mon Sep 17 00:00:00 2001 From: Tomasz Maruszak Date: Fri, 18 Oct 2024 22:44:33 +0200 Subject: [PATCH] Make the Host.Outbox capable of any Key type Signed-off-by: Tomasz Maruszak --- .../DbContextTransactionService.cs | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) 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