Spaces:
Runtime error
Runtime error
File size: 1,578 Bytes
de8b914 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | using System.Data;
using SCM.Application.Common;
namespace SCM.Infrastructure.Persistence;
/// <summary>
/// UoW com escopo de requisição. Abre a conexão de forma preguiçosa e expõe a
/// transação corrente para os repositórios.
/// </summary>
public sealed class UnitOfWork : IUnitOfWork
{
private readonly Lazy<IDbConnection> _connection;
private IDbTransaction? _transaction;
private bool _disposed;
public UnitOfWork(IDbConnectionFactory factory)
{
_connection = new Lazy<IDbConnection>(() =>
{
var connection = factory.CreateConnection();
connection.Open();
return connection;
});
}
public IDbConnection Connection => _connection.Value;
public IDbTransaction? CurrentTransaction => _transaction;
public void BeginTransaction()
=> _transaction ??= Connection.BeginTransaction();
public void Commit()
{
try
{
_transaction?.Commit();
}
finally
{
DisposeTransaction();
}
}
public void Rollback()
{
try
{
_transaction?.Rollback();
}
finally
{
DisposeTransaction();
}
}
private void DisposeTransaction()
{
_transaction?.Dispose();
_transaction = null;
}
public void Dispose()
{
if (_disposed) return;
DisposeTransaction();
if (_connection.IsValueCreated)
_connection.Value.Dispose();
_disposed = true;
}
}
|