Skip to content

Bug: UnitOfWork example contains errors #43

Description

@zetomatoz

The UnitOfWork implementation example contains several issues.

  1. The IUnitOfWork interface declares a Begin method, which is not implemented. Instead, UnitOfWork implements a Start method, which should be renamed Begin.
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();
}
  1. The EnsureConnection method contains a bug that can produce a runtime exception when the Start method gets called because it tries to get a Transaction instance even if the Connection 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();

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions