Open
Description
The UnitOfWork
implementation example contains several issues.
- The
IUnitOfWork
interface declares aBegin
method, which is not implemented. Instead,UnitOfWork
implements aStart
method, which should be renamedBegin
.
public interface IUnitOfWork<TDbConnection>
{
TDbConnection Connection { get; }
DbTransaction Transaction { get ; }
void Begin();
void Rollback();
void Commit();
}
public void Start()
{
if (transaction != null)
{
throw new InvalidOperationException("Cannot start a new transaction while the existing other one is still open.");
}
var connection = EnsureConnection();
transaction = connection.BeginTransaction();
}
- The
EnsureConnection
method contains a bug that can produce a runtime exception when theStart
method gets called because it tries to get aTransaction
instance even if theConnection
instance is not opened yet.
private SqlConnection EnsureConnection() =>
connection ?? connection = new SqlConnection(settings.ConnectionString);
Instead EnsureConnection
should be implemented like that:
private SqlConnection EnsureConnection() =>
connection ??= (SqlConnection) new SqlConnection(settings.ConnectionString).EnsureOpen();