Aspire's configuration flow from AppHost references to environment variables, Microsoft.Extensions.ServiceDiscovery and its configuration provider, the https+http:// scheme and named endpoints, parameters, and how discovery works on Container Apps and Kubernetes.
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.
"There's less magic than people think. Every
WithReferencein the AppHost becomes environment variables on the consuming resource. A database reference becomesConnectionStrings__orders; a project reference becomesservices__catalog__https__0andservices__catalog__http__0with the URLs the orchestrator allocated. Because ASP.NET Core configuration maps double underscores to colons, the service just seesConnectionStrings:ordersandservices:catalog:https:0inIConfiguration. Client integrations likeAddSqlServerDbContext<T>("orders")read exactly that key.For service-to-service HTTP, service defaults call
AddServiceDiscovery()on everyHttpClient. Then I set the base address tohttps+http://catalog. The resolver looks upservices:catalog, and thehttps+httpscheme means: use the HTTPS endpoint if there is one, otherwise HTTP. If the catalog exposes a named endpoint, say a gRPC port calledgrpc, I'd usehttp://_grpc.catalog. Resolved endpoints are cached and refreshed, and with several endpoints the resolver can pick between them.When deployed to Container Apps, the generated Bicep sets the same variables to the apps' internal addresses, and on Kubernetes they point at Service DNS names, so the code is identical everywhere. The mistake I see is people mixing models: hard-coding a URL in
appsettings.jsonthat overrides the injected variable, or renaming a resource in the AppHost and getting a null connection string at the first query. I validate required settings with the options pattern andValidateOnStart, so a wiring mistake fails the deployment instead of the first customer request."
| AppHost | Variable on consumer | Configuration key | Code |
|---|---|---|---|
.WithReference(ordersDb) |
ConnectionStrings__orders |
ConnectionStrings:orders |
AddSqlServerDbContext<OrdersDb>("orders") |
.WithReference(cache) |
ConnectionStrings__cache |
ConnectionStrings:cache |
AddRedisClient("cache") |
.WithReference(catalog) |
services__catalog__https__0 |
services:catalog:https:0 |
new Uri("https+http://catalog") |
.WithEnvironment("Pricing__Region", "au") |
Pricing__Region |
Pricing:Region |
IOptions<PricingOptions> |
AddParameter("api-key", secret: true) + WithEnvironment("ApiKey", p) |
ApiKey |
ApiKey |
options binding |
| Base address | Meaning |
|---|---|
http://catalog |
Use the http endpoint of catalog |
https+http://catalog |
Prefer https, fall back to http (good for local HTTPS, internal HTTP when deployed) |
http://_grpc.catalog |
Use the endpoint named grpc |
| Environment | Who sets the variables | What they point at |
|---|---|---|
Local aspire run |
AppHost / DCP | localhost ports (often through a proxy) |
| Azure Container Apps | Generated Bicep | App names resolved by the environment's internal DNS |
| Kubernetes | Generated manifests / Helm values | Kubernetes Service DNS (catalog.<namespace>.svc) |
After a team renamed catalogdb to catalog in the AppHost, one worker still read GetConnectionString("catalogdb") and failed only when a nightly job ran, [eight hours] after deployment. They added an options class with [Required] connection strings and ValidateOnStart(), and the next mismatch failed the revision's start-up probe within [30 seconds], so Container Apps kept the old revision serving traffic.
Checks whether the candidate understands the mechanism behind Aspire wiring rather than treating it as magic, and can reason about how it behaves once deployed.
Green flags
__ to : mapping.https+http:// scheme and named endpoints.Red flags
AppHost model Orchestrator / manifest Service process
------------- ----------------------- ---------------
api.WithReference(catalog) --> env: services__catalog__https__0 --> IConfiguration["services:catalog:https:0"]
= https://localhost:7231 |
v
HttpClient(BaseAddress = https+http://catalog)
|
ServiceDiscovery handler resolves -> https://localhost:7231
The environment variables configuration provider replaces __ with : because : isn't valid in variable names on every OS. Arrays are just numeric keys, which is why endpoints end in __0, __1. Later providers win, so a value in appsettings.json loses to an environment variable, but a command-line argument would override both.
Microsoft.Extensions.ServiceDiscovery registers a ServiceEndpointResolver. AddServiceDiscovery() on an IHttpClientBuilder inserts a handler that rewrites the request URI when the host is a logical name. Providers are pluggable:
services:{service}:{endpointName}:{index}.AddDnsSrvServiceEndpointProvider): queries SRV records, useful with Kubernetes headless services.Resolved endpoints are cached and refreshed periodically, so changes don't need a restart.
Resources that aren't HTTP services (databases, caches, brokers) expose a connection string expression. Projects expose endpoints. Some resources expose both. Aspire 13 also publishes extra formats for database resources (individual properties, URI and JDBC forms) so non-.NET consumers can use them.
AddParameter("name"): values provided by configuration (Parameters:name) locally and as deployment inputs later.AddConnectionString("legacy-db"): a connection string provided entirely from outside (ConnectionStrings:legacy-db), for resources Aspire doesn't run.Bind settings into options classes with data annotations, call ValidateDataAnnotations().ValidateOnStart(), and the host fails during start-up when a key is missing. On Container Apps or Kubernetes, the failed start-up probe stops the bad revision from taking traffic.
services__* variables.IConfiguration.AsEnumerable() filtered to services: at start-up.https+http://apiservice to http://apiservice and see which endpoint is used.WithEndpoint("grpc", ...) and call it with http://_grpc.apiservice.ValidateOnStart fail fast.Consuming injected configuration safely: connection strings, a discovered HTTP dependency and validated options.
// Orders.Api/Program.cs
using System.ComponentModel.DataAnnotations;
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults(); // includes AddServiceDiscovery for every HttpClient
// Fail at start-up if wiring is wrong, not at the first request.
builder.Services.AddOptions<WiringOptions>()
.Bind(builder.Configuration.GetSection("ConnectionStrings"))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.AddSqlServerDbContext<OrdersDbContext>("orders"); // reads ConnectionStrings:orders
// Logical name; resolved from services:catalog:* (prefers https).
builder.Services.AddHttpClient<CatalogClient>(c => c.BaseAddress = new("https+http://catalog"));
var app = builder.Build();
app.MapDefaultEndpoints();
app.MapGet("/orders/{id:int}/price", async (int id, CatalogClient catalog, CancellationToken ct) =>
Results.Ok(await catalog.GetPriceAsync(id, ct)));
app.Run();
public sealed class WiringOptions
{
[Required] public string? Orders { get; init; }
}
public sealed class CatalogClient(HttpClient http)
{
public Task<decimal> GetPriceAsync(int productId, CancellationToken ct) =>
http.GetFromJsonAsync<decimal>($"/products/{productId}/price", ct);
}
# What the API process actually receives locally (values vary per run)
ConnectionStrings__orders=Server=127.0.0.1,52341;User ID=sa;Password=...;Database=orders;TrustServerCertificate=true
services__catalog__http__0=http://localhost:5231
services__catalog__https__0=https://localhost:7231
OTEL_EXPORTER_OTLP_ENDPOINT=https://localhost:21050
appsettings.json. Why it is wrong: It bypasses discovery and breaks as soon as ports or environments change. Instead: Use the logical name (https+http://catalog) and let configuration supply the address.appsettings.Development.json, appsettings.Test.json and appsettings.Production.json. Why it is wrong: The files drift, a wrong file ships, and environment variables from the platform override them unpredictably. Instead: Keep topology in the AppHost model so every environment gets its addresses the same way; keep only genuine per-environment settings (feature flags, limits) in configuration or App Configuration.AddServiceDiscovery() on the service collection but not on the HttpClient. Why it is wrong: The resolver is registered but the handler isn't in the client pipeline, so catalog is looked up as a real DNS name and fails. Instead: Rely on ConfigureHttpClientDefaults in service defaults, or add it per client.[Required] and ValidateOnStart() so the host refuses to start and logs exactly which key is missing.https+http and assuming traffic is always encrypted. Why it is wrong: It silently falls back to HTTP when no HTTPS endpoint exists, which matters for personal information under the Privacy Act. Instead: Use https:// explicitly where encryption in transit is required, or enforce it at the platform level (Container Apps ingress, mesh mTLS).WithEnvironment("Key", "literal"). Why it is wrong: The literal ends up in source and in generated manifests. Instead: Use secret parameters, backed by user secrets and Key Vault.I like Aspire's approach because it's transparent: it's environment variables and standard IConfiguration, so nothing locks the service to Aspire. A service built this way runs fine under plain Kubernetes as long as someone sets the variables.
On performance: configuration-based resolution happens in memory and results are cached and refreshed periodically, so the per-request overhead is negligible next to the network call. At high load, the costs that matter are DNS lookups (pass-through and SRV providers), connection churn and load distribution. Keep HttpClient instances long-lived through IHttpClientFactory, let SocketsHttpHandler.PooledConnectionLifetime recycle connections so DNS changes are picked up, and remember that client-side choice between endpoints is not a load balancer: in Container Apps and Kubernetes the platform's service address already balances across replicas.
| Discovery option | When it fits | Cost | When not to |
|---|---|---|---|
| Aspire configuration-based discovery | Aspire-managed apps, local and Container Apps | Variables per reference | Very dynamic topologies |
| Platform DNS (pass-through) | Kubernetes or Container Apps names are stable | DNS lookups; no HTTPS preference logic | Local runs without the platform |
| DNS SRV | Kubernetes headless services with named ports | DNS configuration | Platforms without SRV records |
| Service mesh | mTLS, traffic shifting, policy needed | Operating the mesh | Small systems |
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.
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.
Kubernetes runs containers from declarative desired state. A pod is the smallest unit: one or more containers sharing an IP and volumes, and it is disposable. A deployment says "run 3 replicas of this image" and manages ReplicaSets to do rolling updates and rollbacks. A service gives those changing pods a stable DNS name and virtual IP and load-balances across them. Ingress (or the newer Gateway API) routes external HTTP traffic and terminates TLS.
Configuration comes from ConfigMaps and secrets, injected as environment variables or files, which ASP.NET Core reads through IConfiguration. Probes call your health endpoints.
The trade-off: huge flexibility and portability, at the cost of a lot of moving parts to run.
How to tell it (STAR)
**S:** We'd renamed a database resource in our Aspire AppHost, and [eight hours] after the deployment the nightly reconciliation job failed with a missing connection string. **T:** I had to get the job running and make sure a wiring mistake could never hide like that again. **A:** I compared the injected environment variables with what the code read, fixed the name, and then added validated options with `ValidateOnStart` to every service and an AppHost integration test that waits for all resources to be healthy. **R:** The next mismatch, [two months later], failed the build's AppHost test in [under a minute] instead of production at 2 a.m.
Last updated 23 Nov 2026.