IC Improve Code Recipes

Recipe 1.1 · C#

Open Late, Close Early

Problem

Connections are pooled, but only if you give them back. A connection that is opened in a constructor, stored in a field, or closed only on the happy path will eventually exhaust the pool. The symptom is a timeout message about the pool reaching its maximum size, usually under load and usually at the worst time.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: a shared connection closed only on success.
public class CustomerData
{
    private SqlConnection conn = new SqlConnection(
        ConfigurationManager.AppSettings["ConnStr"]);

    public int CountActive()
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(
            "SELECT COUNT(*) FROM Customer WHERE IsActive = 1", conn);
        int count = (int)cmd.ExecuteScalar();
        conn.Close();
        return count;
    }
}

If ExecuteScalar throws, Close() never runs and the connection stays out of the pool until the garbage collector finalizes it. The field also makes the class unsafe to share across threads, and the connection string lookup is buried in a field initializer where nothing can test or replace it.

The improved recipe

C#
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;

namespace ImproveCode.Data;

public interface IDbConnectionFactory
{
    Task<SqlConnection> OpenAsync(CancellationToken ct = default);
}

public sealed class SqlConnectionFactory : IDbConnectionFactory
{
    private readonly string _connectionString;

    public SqlConnectionFactory(string connectionString)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(connectionString);
        _connectionString = connectionString;
    }

    public async Task<SqlConnection> OpenAsync(
        CancellationToken ct = default)
    {
        var connection = new SqlConnection(_connectionString);
        try
        {
            await connection.OpenAsync(ct);
            return connection;
        }
        catch
        {
            await connection.DisposeAsync();
            throw;
        }
    }
}

public sealed class CustomerStats(IDbConnectionFactory db)
{
    public async Task<int> CountActiveAsync(
        CancellationToken ct = default)
    {
        const string sql =
            "SELECT COUNT(*) FROM dbo.Customer WHERE IsActive = 1;";

        await using var connection = await db.OpenAsync(ct);
        await using var command = new SqlCommand(sql, connection);
        object? result = await command.ExecuteScalarAsync(ct);
        return Convert.ToInt32(result);
    }
}

How it works

The factory owns one thing: the connection string. It hands out a new, open connection each time, and the caller owns that connection for the length of one unit of work. await using guarantees DisposeAsync runs whether the method returns or throws, and disposing a pooled connection returns it to the pool. It does not close the physical connection to the server, so opening and disposing per call is cheap.

If OpenAsync fails, the factory disposes the half-built connection before rethrowing, so a failed login never leaks a connection object either.

Register the factory once at startup. In ASP.NET Core it is a singleton because it holds no per-request state:

C#
// Usage snippet: Program.cs
string cs = builder.Configuration.GetConnectionString("AppDb")
    ?? throw new InvalidOperationException("Missing AppDb.");
builder.Services.AddSingleton<IDbConnectionFactory>(
    new SqlConnectionFactory(cs));

The interface is there so a test can hand in a factory that points at a local test database. Chapter 6 covers getting the connection string itself out of source control.

Variations and pitfalls

  • Do not cache the connection. Not in a static field, not in a singleton service, not in HttpContext.Items. Pooling already does the caching, and it does it safely.
  • Pool size. The default maximum is 100 connections per distinct connection string. If you hit it, the fix is almost always a leak or long-running work inside an open connection, not a bigger Max Pool Size.
  • One connection string. Every variation of the string (a different Application Name, a user ID built per request) creates a separate pool. Keep the string constant.
  • Encryption defaults. Starting with version 4 of Microsoft.Data.SqlClient, Encrypt defaults to true. Against a development server with a self-signed certificate you will see a certificate error. Fix the certificate, or set TrustServerCertificate=True for local development only.

On .NET Framework

The same pattern works on .NET Framework 4.6.2 and later with the Microsoft.Data.SqlClient package. On C# 7.3 you write using (var connection = ...) blocks instead of await using declarations, and you call Open() or OpenAsync() the same way.