50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using CPRNIMS.Domain.Contracts.Common;
|
|
using CPRNIMS.Infrastructure.Database;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace CPRNIMS.Domain.Services.Common
|
|
{
|
|
public class TransactionFacade : ITransactionFacade
|
|
{
|
|
private readonly NonInventoryDbContext _db;
|
|
|
|
public TransactionFacade(NonInventoryDbContext db)
|
|
=> _db = db ?? throw new ArgumentNullException(nameof(db));
|
|
|
|
public async Task<T> ExecuteAsync<T>(Func<Task<T>> operation, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(operation);
|
|
|
|
var strategy = _db.Database.CreateExecutionStrategy();
|
|
|
|
return await strategy.ExecuteAsync(async () =>
|
|
{
|
|
await using var tx = await _db.Database.BeginTransactionAsync(ct);
|
|
try
|
|
{
|
|
var result = await operation();
|
|
await _db.SaveChangesAsync(ct);
|
|
await tx.CommitAsync(ct);
|
|
return result;
|
|
}
|
|
catch
|
|
{
|
|
await tx.RollbackAsync(ct);
|
|
throw;
|
|
}
|
|
});
|
|
}
|
|
|
|
public async Task ExecuteAsync(Func<Task> operation, CancellationToken ct = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(operation);
|
|
|
|
await ExecuteAsync<bool>(async () =>
|
|
{
|
|
await operation();
|
|
return true;
|
|
}, ct);
|
|
}
|
|
}
|
|
}
|