- IRepository<T> 구현체: CRUD, 페이징, 조건 검색 지원 - IUnitOfWork 구현체: 트랜잭션 관리 (Begin/Commit/Rollback) - Program.cs에 DI 등록 (AddScoped) Closes #18
51 lines
1.5 KiB
C#
51 lines
1.5 KiB
C#
using Microsoft.EntityFrameworkCore.Storage;
|
|
using SPMS.Domain.Interfaces;
|
|
|
|
namespace SPMS.Infrastructure.Persistence;
|
|
|
|
public class UnitOfWork : IUnitOfWork
|
|
{
|
|
private readonly AppDbContext _context;
|
|
private IDbContextTransaction? _transaction;
|
|
|
|
public UnitOfWork(AppDbContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
|
=> await _context.SaveChangesAsync(cancellationToken);
|
|
|
|
public async Task<IDisposable> BeginTransactionAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
_transaction = await _context.Database.BeginTransactionAsync(cancellationToken);
|
|
return _transaction;
|
|
}
|
|
|
|
public async Task CommitTransactionAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
if (_transaction is null)
|
|
throw new InvalidOperationException("Transaction has not been started.");
|
|
|
|
await _transaction.CommitAsync(cancellationToken);
|
|
await _transaction.DisposeAsync();
|
|
_transaction = null;
|
|
}
|
|
|
|
public async Task RollbackTransactionAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
if (_transaction is null)
|
|
throw new InvalidOperationException("Transaction has not been started.");
|
|
|
|
await _transaction.RollbackAsync(cancellationToken);
|
|
await _transaction.DisposeAsync();
|
|
_transaction = null;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_transaction?.Dispose();
|
|
_context.Dispose();
|
|
}
|
|
}
|