| | | 1 | | // SPDX-FileCopyrightText: 2026 Alper Çelik <[email protected]> |
| | | 2 | | // |
| | | 3 | | // SPDX-License-Identifier: AGPL-3.0-or-later |
| | | 4 | | |
| | | 5 | | using Microsoft.EntityFrameworkCore.Storage; |
| | | 6 | | namespace Api.Database.Utils; |
| | | 7 | | |
| | | 8 | | public interface IEFTransactionDIAccessorService : IAsyncDisposable, IDisposable |
| | | 9 | | { |
| | | 10 | | public IDbContextTransaction BeginOrGetTransaction(); |
| | | 11 | | public Task<IDbContextTransaction> BeginOrGetTransactionAsync(); |
| | | 12 | | } |
| | | 13 | | |
| | 0 | 14 | | public class EFTransactionDIAccessorService(PGContext db) : IEFTransactionDIAccessorService |
| | | 15 | | { |
| | | 16 | | private IDbContextTransaction? _tx; |
| | | 17 | | |
| | | 18 | | public IDbContextTransaction BeginOrGetTransaction() |
| | 0 | 19 | | { |
| | 0 | 20 | | return _tx ?? db.Database.BeginTransaction(); |
| | 0 | 21 | | } |
| | | 22 | | |
| | | 23 | | public async Task<IDbContextTransaction> BeginOrGetTransactionAsync() |
| | 0 | 24 | | { |
| | 0 | 25 | | return _tx ?? await db.Database.BeginTransactionAsync(); |
| | 0 | 26 | | } |
| | | 27 | | |
| | | 28 | | public async ValueTask FinishTransaction() |
| | 0 | 29 | | { |
| | 0 | 30 | | if (_tx is not null) |
| | 0 | 31 | | await _tx.DisposeAsync(); |
| | | 32 | | |
| | 0 | 33 | | _tx = null; |
| | 0 | 34 | | } |
| | | 35 | | |
| | | 36 | | void IDisposable.Dispose() |
| | 0 | 37 | | { |
| | 0 | 38 | | GC.SuppressFinalize(this); |
| | 0 | 39 | | _tx?.Dispose(); |
| | 0 | 40 | | } |
| | | 41 | | |
| | | 42 | | public async ValueTask DisposeAsync() |
| | 0 | 43 | | { |
| | 0 | 44 | | GC.SuppressFinalize(this); |
| | 0 | 45 | | if (_tx is not null) |
| | 0 | 46 | | await _tx.DisposeAsync(); |
| | 0 | 47 | | } |
| | | 48 | | } |