Api-PWA/DocuMed.Repository/Repositories/Base/RepositoryWrapper.cs

71 lines
2.6 KiB
C#
Raw Normal View History

2023-10-10 17:02:38 +03:30
namespace DocuMed.Repository.Repositories.Base;
public class RepositoryWrapper : IRepositoryWrapper
{
private readonly ApplicationContext _context;
2023-10-24 12:45:25 +03:30
private readonly ICurrentUserService _currentUserService;
2023-10-10 17:02:38 +03:30
private IDbContextTransaction? _currentTransaction;
2023-10-24 12:45:25 +03:30
public RepositoryWrapper(ApplicationContext context,ICurrentUserService currentUserService)
2023-10-10 17:02:38 +03:30
{
_context = context;
2023-10-24 12:45:25 +03:30
_currentUserService = currentUserService;
2023-10-10 17:02:38 +03:30
}
2023-10-24 12:45:25 +03:30
public IBaseRepository<T> SetRepository<T>() where T : ApiEntity => new BaseRepository<T>(_context, _currentUserService);
2023-10-10 17:02:38 +03:30
public async Task RollBackAsync(CancellationToken cancellationToken)
{
if (_currentTransaction == null)
throw new ArgumentNullException(nameof(_currentTransaction));
await _currentTransaction.RollbackAsync(cancellationToken);
}
public async Task CommitAsync(CancellationToken cancellationToken)
{
if (_currentTransaction == null)
throw new ArgumentNullException(nameof(_currentTransaction));
await _currentTransaction.CommitAsync(cancellationToken);
}
public async Task BeginTransaction(CancellationToken cancellationToken)
{
_currentTransaction = await _context.Database.BeginTransactionAsync(cancellationToken);
}
public async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
SetAuditables();
await _context.SaveChangesAsync(cancellationToken);
}
private void SetAuditables()
{
IEnumerable<EntityEntry<IApiEntity>> entries = _context.ChangeTracker.Entries<IApiEntity>();
foreach (EntityEntry<IApiEntity> entity in entries)
{
if (entity.State == EntityState.Added)
{
entity.Property(e => e.CreatedAt)
.CurrentValue = DateTime.Now;
2023-10-24 12:45:25 +03:30
if (_currentUserService.UserName != null)
entity.Property(e => e.CreatedBy)
.CurrentValue = _currentUserService.UserName;
2023-10-10 17:02:38 +03:30
}
if (entity.State == EntityState.Modified)
{
2023-10-24 12:45:25 +03:30
if (!entity.Property(e => e.IsRemoved).CurrentValue)
{
entity.Property(e => e.ModifiedAt)
.CurrentValue = DateTime.Now;
if (_currentUserService.UserName != null)
entity.Property(e => e.ModifiedBy)
.CurrentValue = _currentUserService.UserName;
}
2023-10-10 17:02:38 +03:30
}
}
}
public void Dispose()
{
_currentTransaction?.Dispose();
_context?.Dispose();
}
}