skip to content

An ASP.NET Core 10 recipe API already calls AddDbContext<RecipesDbContext>; what happens when Aspire 13's AddNpgsqlDbContext is added, and what should you call instead?

level: seniorimportance: should knowfreq 20%

answer

  1. already registered, in Development only
  2. the Enrich counterpart
  3. EnrichNpgsqlDbContext<RecipesDbContext>
  4. keeps your connection string and lifetime
  5. custom strategy needs DisableRetry

basics

~10 s

In the Development environment AddNpgsqlDbContext throws InvalidOperationException because RecipesDbContext is already registered; elsewhere the check is skipped. Keep the existing registration and call EnrichNpgsqlDbContext<RecipesDbContext>(), which adds retries, a health check and telemetry to it.

solid answer

~40 s

`AddNpgsqlDbContext` first looks for an existing `DbContextOptions<RecipesDbContext>` registration and, only when the environment is Development, throws `InvalidOperationException`: the context "is already registered", use the corresponding `Enrich` method. Outside Development that guard does not run, so the duplicate goes unreported — not something to rely on. The intended path for a context you already register is `builder.EnrichNpgsqlDbContext<RecipesDbContext>()`, called after `AddDbContext`. It keeps your connection string, lifetime and constructor, and adds `EnableRetryOnFailure` (unless `DisableRetry`), an optional `CommandTimeout`, the `RecipesDbContext` health check and Npgsql tracing and metrics. It does not add pooling and does not read `ConnectionStrings` for you. It throws if no context is registered, if you configured a custom execution strategy without setting `DisableRetry`, or if its `CommandTimeout` conflicts with yours.

code

csharp · 14 lines
csharp
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();

// Existing registration stays: per-scope lifetime, ctor takes ICurrentUser too
builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>();
builder.Services.AddDbContext<RecipesDbContext>(o =>
    o.UseNpgsql(builder.Configuration.GetConnectionString("recipesdb")));

// Adds retries, health check, tracing and metrics to it
builder.EnrichNpgsqlDbContext<RecipesDbContext>(s => s.CommandTimeout = 30);

// Do NOT also call this: it throws in Development, and outside it
// proceeds unchecked on top of the existing registration.
// builder.AddNpgsqlDbContext<RecipesDbContext>("recipesdb");

go deeper

for a junior

Recall that there are two methods: AddNpgsqlDbContext registers the context itself, and EnrichNpgsqlDbContext upgrades a context you already registered.

for a middle

Explain what Enrich adds and leaves alone: retries, timeout, health check and telemetry added; connection string, lifetime and pooling untouched; called after AddDbContext.

for a senior

Spot the trap that the duplicate-registration guard only fires in Development, and know Enrich's failure modes with custom execution strategies and conflicting command timeouts.

for a principal

Plan a brownfield adoption path across services: enrich first for low risk, then move contexts to the owning registration once constructors and configuration fit pooling.

## Two ways to get Aspire's defaults onto a DbContext The EF Core client integration `Aspire.Npgsql.EntityFrameworkCore.PostgreSQL` offers two entry points: - `AddNpgsqlDbContext<TContext>(connectionName, configureSettings, configureDbContextOptions)` **owns the registration**: it reads `ConnectionStrings:<connectionName>`, calls `AddDbContextPool<TContext>` with `UseNpgsql`, and adds retries, a health check and telemetry. - `EnrichNpgsqlDbContext<TContext>(configureSettings)` **decorates a registration you already made** with `AddDbContext` (or similar): it adds the same retries, health check and telemetry, and leaves everything else alone. An existing recipe API usually has the second shape already: ```csharp builder.Services.AddDbContext<RecipesDbContext>(o => o.UseNpgsql(builder.Configuration.GetConnectionString("recipesdb"))); ``` ## What happens if you add AddNpgsqlDbContext on top Before registering, `AddNpgsqlDbContext` checks whether `DbContextOptions<RecipesDbContext>` is already in the service collection. The check has two properties worth knowing: 1. **It only runs when `builder.Environment.IsDevelopment()` is true.** In Development the app fails at startup with `InvalidOperationException`: `DbContext<RecipesDbContext> is already registered. Please ensure 'services.AddDbContext<RecipesDbContext>()' is not used when calling 'AddNpgsqlDbContext()' or use the corresponding 'Enrich' method.` 2. **Outside Development it returns without checking**, so Staging or Production start with two overlapping registrations for the same context and nothing reports it; which registration's options take effect then depends on EF Core's registration internals, not on a choice you made. The guard is a developer aid, not a safety net. The fix is to choose one path. ## What EnrichNpgsqlDbContext does Called after your own registration, `builder.EnrichNpgsqlDbContext<RecipesDbContext>()`: - binds `NpgsqlEntityFrameworkCorePostgreSQLSettings` from `Aspire:Npgsql:EntityFrameworkCore:PostgreSQL` and its `RecipesDbContext` sub-section (there is no connection name, so no named sub-section), then runs `configureSettings`; - unless `DisableRetry` is set, adds `EnableRetryOnFailure()` to your `UseNpgsql` options — keeping a strategy you already derived from `NpgsqlRetryingExecutionStrategy`; - applies `CommandTimeout` when the settings carry one; - registers the `RecipesDbContext` health check and Npgsql tracing and metrics, subject to `DisableHealthChecks`, `DisableTracing` and `DisableMetrics`. It **does not** switch you to pooling, change the context's lifetime, or read a connection string: you stay responsible for `UseNpgsql(...)` and for where its string comes from. ## When Enrich throws | Situation | Result | |---|---| | `EnrichNpgsqlDbContext` called before any `AddDbContext` (with retries or a timeout to configure) | `InvalidOperationException` at the Enrich call: the context "was not registered" | | your options set a non-retrying custom execution strategy and `DisableRetry` is `false` | `InvalidOperationException`: `DisableRetry` "needs to be set when a custom Execution Strategy is configured" | | settings `CommandTimeout` differs from a timeout already set in your options | `InvalidOperationException`: conflicting `CommandTimeout` values | The first check runs inside the Enrich call itself. The other two run inside the options callback, so they surface when the context is first resolved, the same moment as the provider's own configuration errors. ## A connection string Enrich does not read Because Enrich leaves `UseNpgsql` to you, the connection string your registration reads is whatever your code asks for. In an Aspire-orchestrated run that is still the injected `ConnectionStrings:recipesdb`, so `GetConnectionString("recipesdb")` keeps working. Two traps follow: - If your registration reads a different key (`ConnectionStrings:Default`, say), the AppHost reference has no effect until you rename the reference with `connectionName` or change the key. - A null connection string is your code's problem now: `UseNpgsql(null)` fails with the provider's own error, not Aspire's "ConnectionString is missing" message. ## Choosing between them | Keep `AddDbContext` + `EnrichNpgsqlDbContext` when | Switch to `AddNpgsqlDbContext` when | |---|---| | the context's constructor takes scoped services, which pooling forbids | the context has a single `DbContextOptions` constructor | | the connection string is built elsewhere, for example from an Npgsql data source | `ConnectionStrings:<name>` is the source of truth | | you need a specific lifetime or options EF pooling cannot reset | you want pooling as well as the Aspire defaults | An incremental migration of a brownfield service usually starts with Enrich — one line, no behaviour change beyond resilience and telemetry — and moves to `AddNpgsqlDbContext` once the context and configuration fit its assumptions.

  • Why might the duplicate registration go unnoticed until production?
    The already-registered guard in `AddNpgsqlDbContext` runs only when the host environment is Development. A team whose local runs use another environment name, or which adds the call in a release branch tested only in Staging, never sees the exception, and the app starts with two overlapping registrations for the same context.
  • Your options already set a custom execution strategy that does not retry. How do you use EnrichNpgsqlDbContext?
    Set `DisableRetry = true` in its settings. Enrich keeps a strategy derived from `NpgsqlRetryingExecutionStrategy`, but any other non-default strategy with retries left on makes it throw `InvalidOperationException`, because adding `EnableRetryOnFailure()` would silently replace your choice.

  • AddNpgsqlDbContext simply overrides an earlier AddDbContext registration in every environment.
  • EnrichNpgsqlDbContext switches the existing context to pooling.
  • EnrichNpgsqlDbContext reads ConnectionStrings:recipesdb and calls UseNpgsql for you.
  • EnrichNpgsqlDbContext can be called before AddDbContext; order does not matter.
  • A custom execution strategy is kept automatically, whatever DisableRetry says.