refactor: modernized GenericRepository and UnitOfWork with newer code from Roma

This commit is contained in:
2025-09-21 00:02:26 +03:00
parent 3b321d0ff4
commit ee94ffa373
8 changed files with 192 additions and 176 deletions

View File

@@ -0,0 +1,16 @@
namespace GamificationService.Database.UnitOfWork;
public interface IUnitOfWork
{
#region Repositories
#endregion
#region Methods
bool SaveChanges();
Task<bool> SaveChangesAsync();
Task BeginTransactionAsync();
Task CommitTransactionAsync();
Task RollbackTransactionAsync();
#endregion
}

View File

@@ -0,0 +1,68 @@
using Microsoft.EntityFrameworkCore.Storage;
namespace GamificationService.Database.UnitOfWork;
public class UnitOfWork : IUnitOfWork
{
#region Fields
private readonly ApplicationContext _context;
private IDbContextTransaction? _transaction;
#endregion
public UnitOfWork(ApplicationContext context)
{
_context = context;
}
#region Repositories
#endregion
#region Save Methods
public bool SaveChanges() => _context.SaveChanges() > 0;
public async Task<bool> SaveChangesAsync() => (await _context.SaveChangesAsync()) > 0;
#endregion
#region Transactions
public async Task BeginTransactionAsync()
{
if (_transaction is not null)
throw new InvalidOperationException("A transaction has already been started.");
_transaction = await _context.Database.BeginTransactionAsync();
}
public async Task CommitTransactionAsync()
{
if (_transaction is null)
throw new InvalidOperationException("A transaction has not been started.");
try
{
await _transaction.CommitAsync();
}
catch
{
await RollbackTransactionAsync();
throw;
}
finally
{
await _transaction.DisposeAsync();
_transaction = null;
}
}
public async Task RollbackTransactionAsync()
{
if (_transaction is null)
return;
await _transaction.RollbackAsync();
await _transaction.DisposeAsync();
_transaction = null;
}
#endregion
}