📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you build a .NET Aspire AppHost? Show how you add projects, SQL Server and Redis containers and references, and what WithReference and WaitFor actually do.

Writing an Aspire AppHost: AddProject, AddSqlServer/AddDatabase, AddRedis, WithReference, WaitFor, data volumes and persistent containers, parameters for secrets, and how references become environment variables.

Junior Coding Intermediate apphost cloud-native dotnet-aspire local-development redis sql-server

🎯 Key points

  • AppHost Program.cs: DistributedApplication.CreateBuilder(args), add resources, builder.Build().Run()
  • AddProject<Projects.X>("name") uses a generated Projects class from the project references; the name becomes the service-discovery name
  • AddSqlServer("sql").AddDatabase("orders") and AddRedis("cache") run containers locally; the resource name is the connection-string name
  • WithReference injects ConnectionStrings__orders for databases and services__api__https__0 style variables for projects
  • WaitFor delays start until the dependency (SQL Server, Redis, another service) is running and healthy; services still need retries for later blips
  • WithDataVolume keeps data between runs; WithLifetime(ContainerLifetime.Persistent) is a local inner-loop optimisation, not a production setting
  • AddParameter("name", secret: true) models secrets: user secrets locally, a secret store such as Key Vault (or a required deployment input) when deployed
  • WithExternalHttpEndpoints, WithReplicas and WithEnvironment shape endpoints, scale and config

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The AppHost is just a console app with the Aspire AppHost SDK. In Program.cs I call DistributedApplication.CreateBuilder(args), add resources, connect them, and call Build().Run(). Projects come in with AddProject<Projects.Orders_Api>("api"): the Projects class 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"), and AddRedis("cache").

The two methods that matter most are WithReference and WaitFor. WithReference(ordersDb) doesn't do anything clever at run time; it adds environment variables to the consumer, here ConnectionStrings__orders, which ASP.NET Core configuration reads as ConnectionStrings:orders. Referencing another project injects its endpoints, like services__api__https__0, which service discovery resolves when the code calls https+http://api. WaitFor delays 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, and WithLifetime(ContainerLifetime.Persistent) so SQL Server isn't recreated every F5. The SA password comes from AddParameter("sql-password", secret: true), backed by user secrets. The mistake I see is people forgetting that resource names are contracts: rename orders in the AppHost and the service's GetConnectionString("orders") silently gets null."


AppHost API cheat sheet

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

What the consumer actually receives

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

Production example

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].

🔍 What the interviewer is checking

Checks that the candidate can actually write an AppHost and understands that references are environment variables and names are contracts.

Green flags

  • Writes AddProject, AddSqlServer().AddDatabase(), AddRedis correctly.
  • Explains what WithReference injects and how configuration reads it.
  • Uses WaitFor and explains the race it prevents.
  • Uses parameters for secrets.

Red flags

  • Hard-codes ports or passwords.
  • Thinks WithReference creates a network proxy or does magic at run time.
  • Can't explain where the connection string comes from.

📚 Learn in depth

1. How the AppHost project is built

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.

2. Resources are a graph

            +---------+   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.

3. Environment variables and configuration

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.

4. Start-up ordering and health

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.

5. Container lifetime and data

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.

6. Parameters

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.

Try it yourself

  1. Build the AppHost below; open the dashboard, click the API resource and read its environment variables.
  2. Remove WaitFor and make SQL Server slow to start; watch the migrations job or API fail on first connection.
  3. Switch SQL Server to a persistent lifetime and time two consecutive AppHost runs.
  4. Rename the database to ordering without changing the API and see what GetConnectionString("orders") returns.
  5. Add a migrations worker and gate the API with WaitForCompletion.

💻 Code

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

⚠ Common mistakes

  • Mistake: Renaming a resource in the AppHost without updating the service. Why it is wrong: The name is the connection-string key, so 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.
  • Mistake: Adding 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.
  • Mistake: Assuming 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).
  • Mistake: Hard-coding the SA password in 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.
  • Mistake: Using persistent containers without a fixed password parameter, or in CI. Why it is wrong: A changed password no longer matches the container's data, and CI needs clean state. Instead: Set the password explicitly and use session lifetime in CI and tests.
  • Mistake: Hard-coding 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.
  • Mistake: Putting business configuration in the AppHost. Why it is wrong: The AppHost models topology; feature settings belong in the service's own configuration. Instead: Use WithEnvironment sparingly, for wiring only.
  • Mistake: Always containerising every dependency. Why it is wrong: Some teams need a shared dev database or a real cloud resource (e.g. a Service Bus namespace) that can't run locally. Instead: Use AddConnectionString("orders") or the integration's existing-resource option to point at an external resource.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the connection string arrives as an environment variable Why: Checks configuration provider order and the __ to : mapping
    How to answer

    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.

    • Hierarchy is flattened with :, e.g. ConnectionStrings:Default.
    • Environment variables use __ 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.

  2. When: Candidate mentions running SQL Server in a container for tests Why: Checks Testcontainers as an alternative for integration tests
    How to answer

    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.

  3. When: Candidate mentions WithReference or service names Why: Checks they understand the mechanism behind references
    How to answer

    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.

↩ Usually asked after

More in .NET Aspire

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me