In ASP.NET Core 10, how should Dapper code obtain its IDbConnection: an injected DbDataSource, a registered connection, or new SqlConnection per call?
answer
- Dapper extends IDbConnection; any DbConnection fits
- one singleton DbDataSource per database
- AddNpgsqlDataSource registers DbConnection, not IDbConnection
- IDbConnection has no OpenAsync or DisposeAsync
- SqlClientFactory.Instance.CreateDataSource(cs)
basics
~20 sInject a singleton DbDataSource and open a DbConnection per query with await using; Dapper's extension methods take it as an IDbConnection. Never share one connection through a singleton, and note AddNpgsqlDataSource registers DbConnection, not IDbConnection.
solid answer
~40 sDapper's methods are extension methods on `IDbConnection`, so any ADO.NET `DbConnection` works; the question is who creates and disposes it. My default is a singleton `DbDataSource`: `AddNpgsqlDataSource(cs)` registers `NpgsqlDataSource` and `DbDataSource` for PostgreSQL, and for SQL Server I register `SqlClientFactory.Instance.CreateDataSource(cs)` as a singleton `DbDataSource`, because Microsoft.Data.SqlClient ships no data source class of its own. Each query method does `await using var conn = await dataSource.OpenConnectionAsync()` and passes `conn` to Dapper. Injecting the transient connection that `AddNpgsqlDataSource` registers also works, but it is registered as `NpgsqlConnection` and `DbConnection`, not `IDbConnection`, so a constructor asking for the interface fails to resolve. `new SqlConnection(cs)` per call is correct thanks to pooling, just less testable. What I never do is `AddSingleton<IDbConnection>(new SqlConnection(cs))`.
go deeper
Know that Dapper works on any DbConnection, and that each query opens its own connection inside await using rather than sharing one.
Compare injecting DbDataSource, a registered connection and new SqlConnection per call, including exactly what AddNpgsqlDataSource registers and what it does not.
Spot singleton-captured connections and IDbConnection-typed code that cannot dispose asynchronously, and set up a SQL Server DbDataSource through SqlClientFactory.
Decide one connection-ownership pattern for every raw-SQL component, so reviews can check lifetimes mechanically instead of case by case.
## What Dapper actually needs Dapper adds extension methods such as `QueryAsync<T>` to `System.Data.IDbConnection`. Every ADO.NET driver connection, `SqlConnection` and `NpgsqlConnection` included, derives from `DbConnection`, which implements that interface. Dapper also handles a **closed** connection for you: if the connection is closed when a call starts, Dapper opens it for that call and closes it again afterwards. So the design question in an ASP.NET Core app is not "how does Dapper connect" but **which component owns the connection's lifetime**. ## Option 1: inject a DbDataSource (the default choice) `DbDataSource` is the BCL's abstract factory for connections. It is thread-safe and meant to live as a singleton: ```csharp // PostgreSQL: NpgsqlDataSource and DbDataSource, both Singleton builder.Services.AddNpgsqlDataSource(builder.Configuration.GetConnectionString("Meters")!); // SQL Server: SqlClient has no DbDataSource subclass; the base DbProviderFactory wraps one builder.Services.AddSingleton<DbDataSource>( SqlClientFactory.Instance.CreateDataSource(builder.Configuration.GetConnectionString("Meters")!)); ``` A query class then holds only the data source, so it can itself be a singleton: ```csharp public sealed class ReadingQueries(DbDataSource dataSource) { public async Task<List<DailyUsage>> DailyAsync(string meterId, DateTime from, DateTime to) { await using var conn = await dataSource.OpenConnectionAsync(); var rows = await conn.QueryAsync<DailyUsage>(DailyUsageSql, new { meterId, from, to }); return rows.AsList(); } } ``` The connection is borrowed for exactly one query and returned to the driver's pool by `await using`. ## Option 2: inject the registered connection `AddNpgsqlDataSource` also registers a **Transient** `NpgsqlConnection`, created closed by the data source, and forwards `DbConnection` to it. The request scope disposes it at the end of the request. Two details catch people: - the registrations are `NpgsqlConnection` and `DbConnection`; `IDbConnection` is **not** registered, and the container does not map interfaces on its own, so a controller asking for `IDbConnection` fails with "Unable to resolve service for type 'System.Data.IDbConnection' while attempting to activate ..."; - the consumer must be scoped or transient, because a singleton would capture one connection. ## Option 3: new SqlConnection(cs) in each method Because SqlClient pools by connection string, `await using var conn = new SqlConnection(cs)` per call is cheap and correct. It scatters connection-string access across classes and makes the provider hard to swap in tests, which is why a data source usually wins. ## The comparison | Approach | Thread-safe to keep in a singleton | Who disposes | Typical use | |---|---|---|---| | Inject `DbDataSource` | yes | your `await using` | default for query classes | | Inject registered `DbConnection` | no | the request scope | one connection per request | | `new SqlConnection(cs)` | the string is | your `await using` | small apps, scripts | | `AddSingleton<IDbConnection>(...)` | no, and shared by all requests | nobody until shutdown | never | ## Lifetimes of the classes around the connection The connection decides how long the class that uses it may live: 1. A query class that holds only a `DbDataSource` may be a singleton, because the data source is thread-safe and each method opens and disposes its own connection. 2. A class that takes the registered `DbConnection` must be scoped or transient, and every method of it shares that one connection object within the request. 3. A class that receives a connection as a **method argument**, such as a helper that runs one statement, owns nothing and leaves disposal to its caller. In tests, the data-source shape is also the easiest to point at a throwaway database: register a different `DbDataSource` and the query classes run unchanged. ## IDbConnection versus DbConnection in signatures `IDbConnection` dates from .NET Framework 1.0: it has `Open`, `Close` and `Dispose`, but no `OpenAsync` and no `DisposeAsync`. A variable typed `IDbConnection` therefore cannot appear in `await using`, and code holding only the interface cannot open asynchronously. Type fields and parameters as `DbConnection` (or the provider type) and let Dapper see them as `IDbConnection` at the call site. ## Two databases Pass a `serviceKey` to register a second data source, for example `AddNpgsqlDataSource(archiveCs, serviceKey: "archive")`, and inject it with `[FromKeyedServices("archive")] NpgsqlDataSource archive`. ## Checklist for a review - every `OpenConnectionAsync()` or `OpenAsync()` sits inside `await using`; - no singleton, static field or cache holds a connection object; - fields and parameters are typed `DbConnection` or `DbDataSource`, not `IDbConnection`; - SQL Server code gets its data source from `SqlClientFactory.Instance.CreateDataSource(cs)` registered once, not per call.
- Why does `await using IDbConnection conn = ...` not compile, while `await using DbConnection conn = ...` does?`await using` needs a type that implements `IAsyncDisposable`. `IDbConnection` extends only `IDisposable`, while the abstract `DbConnection` class implements both and adds `OpenAsync`, `CloseAsync` and `DisposeAsync`. Typing the variable as `DbConnection` keeps disposal and opening asynchronous, and Dapper still accepts it because `DbConnection` implements `IDbConnection`.
- A Dapper query class injects the transient NpgsqlConnection and is registered as a singleton. What goes wrong?The singleton captures one connection object at construction and every request then uses that same instance concurrently, which ADO.NET connections do not support. In Development, scope validation does not catch it, because the connection is transient rather than scoped. Inject `NpgsqlDataSource` or `DbDataSource` instead and open a connection per call.
- Register AddSingleton<IDbConnection>(new SqlConnection(cs)) so Dapper reuses one connection.
- AddNpgsqlDataSource makes IDbConnection injectable for Dapper automatically.
- Dapper fails unless you call Open() on the connection before every query.
- Register the DbDataSource as Scoped so each request gets its own data source.
- IDbConnection supports await using, so type every field as the interface.