skip to content

Your WebApplicationFactory adds the Testcontainers connection string with ConfigureAppConfiguration, yet the ASP.NET Core 10 app still connects to localhost:5432 — why, and how do you fix it?

level: seniorimportance: should knowfreq 28%

answer

  1. when does Program.cs read the value
  2. a local captured before Build()
  3. app configuration replayed at Build
  4. host settings arrive as command-line args
  5. UseSetting needs args passed to CreateBuilder

basics

~20 s

Program.cs reads the connection string into a local before builder.Build(), but ConfigureAppConfiguration sources from WebApplicationFactory are applied only at Build. Use builder.UseSetting or ConfigureHostConfiguration instead, which reach the app as command-line arguments before Program.cs runs.

solid answer

~40 s

With minimal hosting, `WebApplicationFactory<Program>` runs the real Program.cs and replays its `ConfigureWebHost` callbacks into the app's builder. A source added with `ConfigureAppConfiguration` is applied when `builder.Build()` runs, so a line like `var cs = builder.Configuration.GetConnectionString("Orders");` placed before `Build()` has already captured the appsettings value, `Host=localhost;Port=5432`. Values set with `builder.UseSetting("ConnectionStrings:Orders", _db.GetConnectionString())`, or with `ConfigureHostConfiguration` in a `CreateHost` override, become command-line arguments passed to the entry point, so `WebApplication.CreateBuilder(args)` has them from the start and they win over appsettings.json. That requires Program.cs to pass `args`. Alternatively, read configuration lazily inside the `AddDbContext` lambda. The `ConfigureWebApplicationBuilder` hook that fixes this ordering exists only in .NET 11 previews, not in 10.

code

csharp · 14 lines
csharp
// Test project: the value reaches Program.cs as --ConnectionStrings:Orders=...
protected override void ConfigureWebHost(IWebHostBuilder builder) =>
    builder.UseSetting("ConnectionStrings:Orders", _db.GetConnectionString());

// Or, for several values at once:
protected override IHost CreateHost(IHostBuilder builder)
{
    builder.ConfigureHostConfiguration(c => c.AddInMemoryCollection(
    [
        new("ConnectionStrings:Orders", _db.GetConnectionString()),
        new("Orders:SeedDemoData", "false")
    ]));
    return base.CreateHost(builder);
}

go deeper

for a junior

Remember that the test's connection string must reach the app before the app reads it, and that UseSetting is the simplest way to pass it.

for a middle

Explain the two timings: host settings become command-line arguments at CreateBuilder, while app-configuration callbacks are replayed at Build.

for a senior

Diagnose from the symptom: find where Program.cs reads the value, prefer UseSetting or lazy reads, check that args are passed, and never fork Program.cs for tests.

for a principal

Set a team rule that Program.cs reads configuration lazily and never branches on a test environment, so every test harness can supply values the same way.

## The symptom The order API's integration tests start a PostgreSQL container with Testcontainers and hand its connection string to `WebApplicationFactory<Program>`: ```csharp protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureAppConfiguration(c => c.AddInMemoryCollection( [new("ConnectionStrings:Orders", _db.GetConnectionString())])); ``` The first request fails with a connection refused on `localhost:5432`, the developer's local database from appsettings.Development.json. The container is running; the app never used its string. ## How WebApplicationFactory reaches a minimal-hosting app A top-level-statements Program.cs creates its own `WebApplicationBuilder`; the factory cannot hand it a pre-made builder. Instead it: 1. collects **host configuration** (from `ConfigureHostConfiguration`, and from `UseSetting` on the `IWebHostBuilder`) immediately; 2. converts that host configuration into **command-line arguments**, one `--key=value` per setting, and runs the entry point with them; 3. records every other callback, including `ConfigureAppConfiguration` and `ConfigureServices`, and **replays them when the app calls `builder.Build()`**. So the two kinds of setting arrive at different times: | Mechanism in the factory | Visible to Program.cs | Survives as a source | |---|---|---| | `builder.UseSetting(key, value)` | from `CreateBuilder(args)` on | as a command-line value | | `ConfigureHostConfiguration` in `CreateHost` | from `CreateBuilder(args)` on | as a command-line value | | `ConfigureAppConfiguration` | only once `Build()` runs | yes, as the added source | ## Why the app missed the value Program.cs had: ```csharp var cs = builder.Configuration.GetConnectionString("Orders"); builder.Services.AddDbContext<OrdersDbContext>(o => o.UseNpgsql(cs)); var app = builder.Build(); ``` The local `cs` is read **before** `Build()`, when the replayed `ConfigureAppConfiguration` source has not been added yet. The lambda later captures that stale string. Any registration that takes a value eagerly, such as `AddNpgsqlDataSource(connectionString)`, has the same problem. ## Fixes, in order of preference - **Use `UseSetting`** in `ConfigureWebHost`. It is one line, the value arrives as a command-line argument, and command-line arguments come after the JSON files in `WebApplication.CreateBuilder`, so they override appsettings.json. - **Override `CreateHost`** and call `builder.ConfigureHostConfiguration(c => c.AddInMemoryCollection(...))` before `base.CreateHost(builder)`, when several values must be passed. Same mechanism, same timing. - **Read lazily in the app.** `AddDbContext<OrdersDbContext>((sp, o) => o.UseNpgsql(sp.GetRequiredService<IConfiguration>().GetConnectionString("Orders")))` reads configuration when `DbContextOptions` are resolved, after the replayed sources were added. This also makes the app friendlier to other configuration sources. Two conditions apply to the first two fixes: 1. Program.cs must call `WebApplication.CreateBuilder(args)`; without `args` the command-line values are dropped. The templates pass it. 2. The container must be started before the host is built, because `UseSetting` reads `GetConnectionString()` when `ConfigureWebHost` runs. ## What not to do - Do not add `if (builder.Environment.IsEnvironment("Testing"))` branches that build a different string in Program.cs; the app then tests a path production never takes. - Do not reach for the `ConfigureWebApplicationBuilder` override shown in current docs. It arrives with .NET 11 previews; `Microsoft.AspNetCore.Mvc.Testing` 10.0.12 does not have it. - Do not replace the `DbContext` registration in `ConfigureTestServices` just to change the string; that works but hides the real configuration path the tests should exercise, and service replacement is a separate tool. ## Proving which value the app used When the symptom is unclear, ask the built app rather than guessing: - resolve `IConfiguration` from `factory.Services` and call `GetConnectionString("Orders")`; if it shows the container's port, configuration is right and the stale value was captured in a local before `Build()`; - resolve `OrdersDbContext` in a scope and read `Database.GetConnectionString()`, which shows the string the context will actually open; - compare the two: different values point straight at an eager read in Program.cs. The same reasoning applies to any value the app reads before `Build()`: feature flags that decide which services are registered, URLs passed to `AddHttpClient`, and options bound once into a local. If the app needs it before `Build()`, the test must deliver it as host configuration.

  • Why do UseSetting values override appsettings.json?
    `WebApplicationFactory` passes them to the entry point as command-line arguments, and `WebApplication.CreateBuilder(args)` adds the command-line source after the JSON files and environment variables. A later source wins for the same key, so `ConnectionStrings:Orders` from the test replaces the one in appsettings.Development.json.
  • Program.cs calls WebApplication.CreateBuilder() with no arguments. What happens to UseSetting?
    The factory still builds the `--key=value` arguments and calls the entry point with them, but Program.cs never passes them to the builder, so the values never become configuration. The app silently keeps its own connection string. Pass `args`, as the templates do, or read the value lazily and use `ConfigureAppConfiguration`.

  • ConfigureAppConfiguration in ConfigureWebHost runs before any line of Program.cs.
  • Override ConfigureWebApplicationBuilder in the .NET 10 factory to set the string.
  • UseSetting values are applied only after the app calls Build().
  • Program.cs can call CreateBuilder() without args and still receive UseSetting values.
  • Add an IsEnvironment("Testing") branch in Program.cs that reads a test-only key.

Assumes ASP.NET Core 10 with Microsoft.AspNetCore.Mvc.Testing 10.0.12; a ConfigureWebApplicationBuilder override that applies configuration right after CreateBuilder appears only in .NET 11 previews.