Files
HealthAppRepositoryB/src/HealthApp.Infrastructure/RequestTransaction.cs
T

35 lines
1.6 KiB
C#

using System.Data;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace HealthApp.Infrastructure;
// Coordinates mechanics only; it has no health table/query or access-policy knowledge.
public sealed class RequestTransaction(NpgsqlDataSource source) : IAsyncDisposable
{
public NpgsqlConnection? Connection { get; private set; }
public NpgsqlTransaction? Transaction { get; private set; }
public bool Active => Transaction is not null;
public async Task BeginAsync(bool write, CancellationToken ct)
{
if (Active) return;
Connection = await source.OpenConnectionAsync(ct);
Transaction = await Connection.BeginTransactionAsync(write ? IsolationLevel.ReadCommitted : IsolationLevel.RepeatableRead, ct);
}
public async Task EnlistAsync(DbContext context, CancellationToken ct)
{
if (Transaction is null || Connection is null) throw new InvalidOperationException("No request transaction.");
if (context.Database.GetDbConnection() != Connection) context.Database.SetDbConnection(Connection, false);
await context.Database.UseTransactionAsync(Transaction, ct);
}
public async Task FinishAsync(CancellationToken ct)
{
if (Transaction is null) return;
await Transaction.CommitAsync(ct); await Transaction.DisposeAsync(); Transaction = null;
await Connection!.DisposeAsync(); Connection = null;
}
public async ValueTask DisposeAsync()
{
if (Transaction is not null) { await Transaction.DisposeAsync(); Transaction = null; }
if (Connection is not null) { await Connection.DisposeAsync(); Connection = null; }
}
}