Writing an Aspire AppHost: AddProject, AddSqlServer/AddDatabase, AddRedis, WithReference, WaitFor, data volumes and persistent containers, parameters for secrets, and how references become environment variables.
The AppHost's Program.cs creates a DistributedApplication builder, adds resources, links them and runs:
AddProject<Projects.Orders_Api>("api") adds a project; the name becomes its service-discovery name.AddSqlServer("sql").AddDatabase("orders") and AddRedis("cache") run containers locally; the resource name is the connection-string name.WithReference(db) injects ConnectionStrings__orders; WithReference(api) injects services__api__https__0, the endpoint.WaitFor(db) holds start-up until the database is healthy.Add WithDataVolume() to keep data, ContainerLifetime.Persistent to avoid restarting slow containers, and AddParameter(..., secret: true) for passwords. The trade-off: references are simple, but every name is a contract between the AppHost and the service's configuration.
"The AppHost is just a console app with the Aspire AppHost SDK. In
Program.csI callDistributedApplication.CreateBuilder(args), add resources, connect them, and callBuild().Run(). Projects come in withAddProject<Projects.Orders_Api>("api"): theProjectsclass is generated from the AppHost's project references, and the string name is what other services use to discover it. Backing services are containers:AddSqlServer("sql")then.AddDatabase("orders"), andAddRedis("cache").The two methods that matter most are
WithReferenceandWaitFor.WithReference(ordersDb)doesn't do anything clever at run time; it adds environment variables to the consumer, hereConnectionStrings__orders, which ASP.NET Core configuration reads asConnectionStrings:orders. Referencing another project injects its endpoints, likeservices__api__https__0, which service discovery resolves when the code callshttps+http://api.WaitFordelays starting the consumer until the dependency is running and healthy, which fixes the classic race where the API starts before SQL Server accepts connections.For a nicer inner loop I add
WithDataVolume()so the database survives restarts, andWithLifetime(ContainerLifetime.Persistent)so SQL Server isn't recreated every F5. The SA password comes fromAddParameter("sql-password", secret: true), backed by user secrets. The mistake I see is people forgetting that resource names are contracts: renameordersin the AppHost and the service'sGetConnectionString("orders")silently gets null."
| API | What it does |
|---|---|
AddProject<T>("name") |
Runs a .NET project as a process; name = discovery name |
AddContainer("name", "image", "tag") |
Runs any container image |
AddSqlServer / AddPostgres / AddRedis |
Hosting integrations with sensible defaults and health checks |
.AddDatabase("orders") |
A child database resource; its connection string includes the database name |
WithReference(r) |
Injects connection string or endpoints into the consumer |
WaitFor(r) / WaitForCompletion(r) |
Start ordering on health, or on a one-off job finishing (e.g. migrations) |
WithDataVolume() |
Named volume so data survives |
WithLifetime(ContainerLifetime.Persistent) |
Container keeps running when the AppHost stops |
AddParameter("x", secret: true) |
A configurable value; locally from Parameters:x in user secrets |
WithEnvironment("KEY", value) |
Extra environment variables |
WithExternalHttpEndpoints() |
Marks endpoints as public when deployed |
WithReplicas(3) |
Runs several instances locally |
| AppHost line | Environment variable in the API | Read with |
|---|---|---|
.WithReference(ordersDb) |
ConnectionStrings__orders=Server=127.0.0.1,52341;...;Database=orders |
GetConnectionString("orders") |
.WithReference(cache) |
ConnectionStrings__cache=localhost:52342 |
AddRedisClient("cache") |
.WithReference(api) |
services__api__https__0=https://localhost:7123 |
https+http://api with service discovery |
A team's integration environment had a flaky first run: the worker started before SQL Server was ready and crashed [about one time in three]. Adding WaitFor(ordersDb) and a migrations project with WaitForCompletion made start-up deterministic, and persistent containers cut the AppHost restart time from [about 40 seconds] to [under 10].
Checks that the candidate can actually write an AppHost and understands that references are environment variables and names are contracts.
Green flags
AddProject, AddSqlServer().AddDatabase(), AddRedis correctly.WithReference injects and how configuration reads it.WaitFor and explains the race it prevents.Red flags
WithReference creates a network proxy or does magic at run time.The AppHost project uses the Aspire AppHost SDK (<Project Sdk="Aspire.AppHost.Sdk/13.x.y">); since Aspire 13 the SDK brings in the hosting package itself. Each <ProjectReference> to a service generates a type under the Projects namespace (dots become underscores), carrying the path to the .csproj. That's how AddProject<Projects.Orders_Api> knows what to build and run.
+---------+ WithReference +------------+
| worker | ----------------> | orders db | <-- child of sql (container)
+---------+ +------------+
| WithReference ^
v | WithReference + WaitFor
+---------+ -------------------->-+
| api | -----> cache (redis container)
+---------+
Each node exposes endpoints and a connection string expression. A reference evaluates that expression when the consumer starts, so ports allocated at run time flow through correctly.
ASP.NET Core maps __ in environment variable names to : in configuration keys. ConnectionStrings__orders becomes ConnectionStrings:orders, and services__api__https__0 becomes services:api:https:0, which the service-discovery configuration provider reads. Aspire 13 also exposes extra formats (for example URI and JDBC forms for database resources) so Python, JavaScript and Java resources can consume the same references.
Hosting integrations register health checks for their resources (e.g. a SQL Server connection check). WaitFor waits for the resource to be running and those checks to pass. WaitForCompletion waits for a resource to exit successfully, which is the pattern for a migration runner or seeding job.
By default containers are created when the AppHost starts and removed when it stops. WithDataVolume() attaches a named volume. ContainerLifetime.Persistent leaves the container running, and Aspire re-attaches to it next time if the configuration hasn't changed. Persistent containers need a stable password, which is why you set the parameter explicitly instead of letting Aspire generate one.
AddParameter("sql-password", secret: true) creates a resource whose value comes from configuration under Parameters:sql-password (user secrets locally). In deployment it becomes a required input (a Bicep parameter or a prompt), so secrets never live in the AppHost code.
WaitFor and make SQL Server slow to start; watch the migrations job or API fail on first connection.ordering without changing the API and see what GetConnectionString("orders") returns.WaitForCompletion.An AppHost with a secret parameter, persistent SQL Server, Redis, a migrations job and two projects.
// AppHost/Program.cs
var builder = DistributedApplication.CreateBuilder(args);
// Secret comes from user secrets locally: Parameters:sql-password
var sqlPassword = builder.AddParameter("sql-password", secret: true);
var sql = builder.AddSqlServer("sql", password: sqlPassword)
.WithDataVolume()
.WithLifetime(ContainerLifetime.Persistent); // don't recreate on every F5
var ordersDb = sql.AddDatabase("orders"); // name = connection-string name
var cache = builder.AddRedis("cache");
// One-off job that applies EF Core migrations, then exits.
var migrations = builder.AddProject
GetConnectionString("orders") returns null and the app fails at first query. Instead: Treat names as contracts; keep them in constants or fail fast at start-up.WaitFor for SQL Server but not for Redis, a broker or another service. Why it is wrong: The same start-up race happens with any dependency: the first cache call or message publish fails and some code paths swallow it. Instead: WaitFor every dependency the service needs to start, and use hosting integrations that register health checks.WaitFor means connections can never fail. Why it is wrong: It only gates start-up; a container restart or network blip later still breaks calls. Instead: Keep connection resiliency (EnableRetryOnFailure for EF Core, the standard resilience handler for HTTP, Redis reconnect settings).Program.cs. Why it is wrong: It ends up in git and in generated deployment artefacts. Instead: Use AddParameter(..., secret: true) with user secrets locally and Key Vault or a required deployment parameter when deployed.https://localhost:7123 in an HttpClient. Why it is wrong: Ports are allocated by the orchestrator and differ per machine and in deployment. Instead: Use https+http://api with service discovery.WithEnvironment sparingly, for wiring only.AddConnectionString("orders") or the integration's existing-resource option to point at an external resource.I keep the AppHost boring and declarative: topology, references and wiring only. Anything that feels like logic belongs in the services. The best signal that it's right is that a new joiner can read Program.cs and draw the system.
| Choice | When it fits | Cost | When not to |
|---|---|---|---|
WaitFor |
Any dependency that must be ready | Slower total start | Optional dependencies the service tolerates being down |
WaitForCompletion on a migrations job |
EF Core migrations or seeding locally | One more project | Production deployments that run migrations in the pipeline |
| Persistent containers | Slow-starting databases | Stale containers if config drifts | CI, where clean state matters |
| Data volumes | Keeping dev data | Disk; needs occasional reset | Tests that need a clean database |
ASP.NET Core configuration is a layered key-value store. IConfiguration merges an ordered list of providers into one flat, case-insensitive dictionary. WebApplication.CreateBuilder adds, in order: appsettings.json, appsettings.{Environment}.json, user secrets (only in Development), environment variables and command-line arguments. When two providers set the same key, the one added last wins, so an environment variable on the server overrides the JSON file you shipped.
:, e.g. ConnectionStrings:Default.__ instead, e.g. ConnectionStrings__Default, because : is not allowed in Linux variable names.The trade-off: layering lets one build artifact run everywhere, but a value can come from five places, so you need to know the order to find out which one won.
Add the Testcontainers.MsSql package. In an xUnit collection fixture that implements IAsyncLifetime, build an MsSqlContainer with a pinned image, await StartAsync() in InitializeAsync, and await DisposeAsync() in teardown (Testcontainers' Ryuk reaper also removes orphaned containers if a CI job dies). Pass GetConnectionString() to a WebApplicationFactory by overriding configuration, apply EF Core migrations once, and reset data between tests with Respawn. If the container fails to start (for example the CI agent has no Docker), fail fast with a clear message rather than skipping. Each run gets a clean, real SQL Server, catching translation and constraint bugs that the in-memory provider hides.
Aspire wiring is environment variables plus normal .NET configuration. When the AppHost says api.WithReference(ordersDb), Aspire sets ConnectionStrings__orders on the API; WithReference(catalog) sets services__catalog__https__0=https://localhost:7231. ASP.NET Core turns __ into :, so code reads GetConnectionString("orders").
For HTTP calls, Microsoft.Extensions.ServiceDiscovery hooks into HttpClient: a base address of https+http://catalog is resolved from services:catalog:*, preferring HTTPS and falling back to HTTP. http://_grpc.catalog picks a named endpoint.
When deployed, the generated Container Apps or Kubernetes manifests set the same variables to platform addresses, so the code doesn't change. The trade-off: simple and transparent, but resource names become contracts and misconfiguration only shows up at run time unless you validate at start-up.
Last updated 23 Nov 2026.