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

📚 Interview question

How does Aspire service discovery and configuration work? Explain how connection strings and endpoints reach each service, what the https+http:// scheme means, and how the same code finds its dependencies when deployed.

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.

Intermediate Theory Intermediate cloud-native configuration dotnet-aspire environment-variables httpclient service-discovery

🎯 Key points

  • References in the AppHost become environment variables: ConnectionStrings__name for resources, services__name__scheme__index for project endpoints
  • ASP.NET Core configuration maps __ to :, so services read them through normal IConfiguration and GetConnectionString
  • Microsoft.Extensions.ServiceDiscovery plugs into HttpClient; AddServiceDiscovery() on a client resolves logical names like http://catalog
  • https+http://catalog means prefer HTTPS and fall back to HTTP, so it can silently send plain HTTP; use https:// where encryption is required
  • The default configuration provider reads services:{name}:{endpoint}:{index}; a DNS SRV provider exists for Kubernetes; results are cached, so per-request cost is negligible
  • When deployed, the generated manifests set the same variables to platform addresses (Container Apps internal names, Kubernetes Service DNS), so code doesn't change between environments
  • Parameters (AddParameter) and AddConnectionString model values supplied from outside; validate required settings at start-up with ValidateOnStart

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"There's less magic than people think. Every WithReference in the AppHost becomes environment variables on the consuming resource. A database reference becomes ConnectionStrings__orders; a project reference becomes services__catalog__https__0 and services__catalog__http__0 with the URLs the orchestrator allocated. Because ASP.NET Core configuration maps double underscores to colons, the service just sees ConnectionStrings:orders and services:catalog:https:0 in IConfiguration. Client integrations like AddSqlServerDbContext<T>("orders") read exactly that key.

For service-to-service HTTP, service defaults call AddServiceDiscovery() on every HttpClient. Then I set the base address to https+http://catalog. The resolver looks up services:catalog, and the https+http scheme means: use the HTTPS endpoint if there is one, otherwise HTTP. If the catalog exposes a named endpoint, say a gRPC port called grpc, I'd use http://_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.json that 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 and ValidateOnStart, so a wiring mistake fails the deployment instead of the first customer request."


From AppHost line to running code

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

Resolution schemes

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

Where the addresses come from

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)

Production example

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.

🔍 What the interviewer is checking

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

  • Explains references as environment variables and the __ to : mapping.
  • Knows the https+http:// scheme and named endpoints.
  • Explains how deployed environments get the same variables.
  • Validates configuration at start-up.

Red flags

  • Thinks Aspire runs a proxy or mesh in production.
  • Hard-codes URLs as a workaround.
  • Can't say where a connection string comes from.

📚 Learn in depth

1. The flow end to end

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

2. Configuration mapping

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.

3. How the resolver works

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:

  • Configuration provider (default): reads services:{service}:{endpointName}:{index}.
  • Pass-through: if nothing matches, the name is used as a normal host name, which works with platform DNS.
  • DNS SRV provider (AddDnsSrvServiceEndpointProvider): queries SRV records, useful with Kubernetes headless services.

Resolved endpoints are cached and refreshed periodically, so changes don't need a restart.

4. Connection strings vs endpoints

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.

5. Things that come from outside

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

6. Validating at start-up

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.

Try it yourself

  1. In a starter solution, open the dashboard, select the web front end and read its services__* variables.
  2. Log IConfiguration.AsEnumerable() filtered to services: at start-up.
  3. Change the base address from https+http://apiservice to http://apiservice and see which endpoint is used.
  4. Add a named endpoint with WithEndpoint("grpc", ...) and call it with http://_grpc.apiservice.
  5. Add a required options class and rename the resource in the AppHost to see ValidateOnStart fail fast.

💻 Code

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

⚠ Common mistakes

  • Mistake: Hard-coding a dependency URL in 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.
  • Mistake: Keeping per-environment URLs in 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.
  • Mistake: Thinking service discovery is a network proxy or service mesh. Why it is wrong: It only resolves names to addresses inside the client; it adds no mTLS, retries or traffic shifting. Instead: Use the resilience handler for retries and the platform or a mesh for mTLS.
  • Mistake: Calling 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.
  • Mistake: Not validating required connection strings, or wrapping registration in try/catch and carrying on. Why it is wrong: A renamed resource surfaces as a null reference at the first query, possibly hours after deployment, and swallowing the error just moves the failure. Instead: Options with [Required] and ValidateOnStart() so the host refuses to start and logs exactly which key is missing.
  • Mistake: Using 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).
  • Mistake: Putting secrets in 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.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions WithReference Why: Checks hands-on AppHost knowledge
    How to 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.

  2. When: Candidate explains environment variables overriding appsettings Why: Checks configuration provider order
    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.

  3. When: Candidate mentions Kubernetes Service DNS Why: Checks how requests and configuration reach a pod
    How to answer

    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.

🛠 Real-world problems: how you handle them

Renamed Aspire resource broke a nightly job eight hours after deployment
Situation
[Orders platform] with [an API and three workers] on Azure Container Apps in Australia East, modelled in an Aspire AppHost. A refactor renamed the `catalogdb` resource to `catalog`.
Signals
No errors at deployment. At [02:00] the nightly reconciliation worker threw `InvalidOperationException: The ConnectionString property has not been initialized`; Container Apps logs showed repeated restarts and an alert fired on the failed-job count.
Investigation
Compared the worker revision's environment variables in the Azure portal with the API's; saw `ConnectionStrings__catalog` but code read `catalogdb`. Confirmed locally in the Aspire dashboard's resource details. Searched the repo for every `GetConnectionString` and client-integration name.
Resolution
Immediate: hot-fixed the worker to read `catalog` and re-ran the job. Real fix: options classes with `[Required]` connection strings and `ValidateOnStart()` in every service, plus resource names in a shared constants class used by both AppHost and services.
Prevention
Start-up validation makes bad revisions fail their start-up probe; an integration test using `DistributedApplicationTestingBuilder` starts the AppHost and asserts every service becomes healthy; code-review checklist item for AppHost renames.

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.

↩ Usually asked after

More in .NET Aspire

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me