Module 5: Aspire, Containers, and Shipping

3:45 – 4:40 PM · Concepts 20 min · Lab 30 min (about 40 if you do every step)

▶ Present this module

Learning objectives

By the end of this module you can add a .NET Aspire AppHost to orchestrate the API and its dependencies locally, see the day's telemetry in the dashboard, build a container image without a Dockerfile, version the API, and describe the path to a cloud deployment.

What Aspire is, and is not

.NET Aspire is three things for local development: an orchestrator that starts your projects and their dependencies (databases, caches, message brokers) together; service discovery so the API finds the payment service by name instead of a hard-coded port; and a dashboard that shows logs, traces, and metrics from everything it started.

It is not a deployment target. It produces a manifest that tools such as azd turn into real infrastructure, but Aspire itself runs on your laptop.

flowchart TB
    AH[Roastery.AppHost] --> API[Roastery.Api]
    AH --> PAY[Roastery.Payments]
    AH -.->|stretch| PG[(Postgres container)]
    API -->|service discovery| PAY
    API --> SD[ServiceDefaults\nOTel · health · resilience]
    PAY --> SD
    AH --> DASH[Aspire Dashboard]
    API -.->|OTLP| DASH
    PAY -.->|OTLP| DASH

The two projects Aspire adds

Roastery.AppHost is a tiny program (AppHost.cs) that describes the system:

var builder = DistributedApplication.CreateBuilder(args);

var payments = builder.AddProject<Projects.Roastery_Payments>("payments");

builder.AddProject<Projects.Roastery_Api>("api")
       .WithReference(payments)
       .WaitFor(payments)
       .WithEnvironment("Payments__BaseUrl", "https+http://payments")
       .WithExternalHttpEndpoints();

builder.Build().Run();

WithReference(payments) injects the payment service's address into the API's configuration as services__payments__https__0, and WaitFor(payments) holds the API back until payments is running. On the API side, AddServiceDiscovery() teaches HttpClient to resolve a base address of https+http://payments to that injected address. The https+http:// scheme means "prefer the HTTPS endpoint, fall back to HTTP", and payments is the resource name from the AppHost.

The API still reads its payment address from Payments:BaseUrl, and appsettings.json still sets it to https://localhost:7281 so the API runs on its own. WithEnvironment("Payments__BaseUrl", "https+http://payments") replaces that value when the AppHost starts the API, because environment variables override appsettings.json. Under Aspire the client then asks for payments by name and discovery supplies the address. Without that line the appsettings.json URL would win and discovery would never run.

Roastery.ServiceDefaults is a class library with one extension method that every service calls:

builder.AddServiceDefaults();   // OpenTelemetry, health checks, service discovery, resilience defaults
// …
app.MapDefaultEndpoints();      // /health and /alive

This is where the OpenTelemetry block and the health checks from Lab 4 belong. You wrote them by hand so you would know what the template does; now you let the template do it. The template also gives every HttpClient a standard resilience handler and service discovery through ConfigureHttpClientDefaults, so a per-client AddStandardResilienceHandler() from Lab 4 now stacks a second retry pipeline on top of the first. Remove the per-client one.

The dashboard

When you press F5 on the AppHost (or run aspire run), the dashboard opens with every resource, its state, and its endpoints. If the browser does not open or asks for a token, use the login URL with the ?t= token that the console prints. Place an order and open Traces: the request to /api/orders is a waterfall that includes the HttpClient call to payments, the matching POST /charge span inside the payment service, and the repeated attempts from the resilience handler when the fake provider fails. Structured logs shows every log line from both services, including the OrderReadyNotifier entry when an order is marked ready.

This is the payoff for Module 4. Nothing was added to make this visible; the instrumentation was already there.

Two things are deliberately not in the trace. EF Core queries do not appear as spans, because neither Lab 4 nor ServiceDefaults registers EF Core instrumentation. And the notifier's log entry is not linked to the PUT that triggered it: the message crosses a Channel, and nothing carries the trace context across. Both are stretch goals in the lab.

A container image with no Dockerfile

The .NET SDK can publish an OCI image directly:

dotnet publish src/Roastery.Api -c Release \
    --os linux /t:PublishContainer \
    -p:ContainerRepository=roastery-api

Without --arch the image matches your machine (arm64 on Apple Silicon). Add --arch x64 when the image is headed for an x64 host.

docker run --rm -p 8080:8080 \
  -e ASPNETCORE_ENVIRONMENT=Development \
  -e ConnectionStrings__Roastery="Data Source=/tmp/roastery.db" \
  -e Jwt__SigningKey="$JWT_KEY" \
  -e Payments__BaseUrl="https://host.docker.internal:7281" \
  roastery-api

ASPNETCORE_ENVIRONMENT=Development is there because Roastery only migrates and seeds its database in Development, and MapDefaultEndpoints() only maps /health and /alive in Development. A real deployment would run migrations as a separate step instead. On Linux, add --add-host=host.docker.internal:host-gateway so the container can reach the host.

What the SDK chose for you: a mcr.microsoft.com/dotnet/aspnet:10.0 base image, a non-root user, port 8080, and a layer per publish output. Every one of those is overridable with an MSBuild property when you need it, and none of them require you to maintain a Dockerfile.

The non-root user matters for SQLite: the app user cannot write to the app folder, which is why the connection string points at /tmp. To keep the database in a named volume instead, the volume's directory has to be owned by that user (UID 1654), because Docker creates a new volume owned by root:

docker run --rm -v roastery-data:/data alpine chown 1654:1654 /data
# then add to the run command:
#   -v roastery-data:/data -e ConnectionStrings__Roastery="Data Source=/data/roastery.db"

The double-underscore environment variables (Jwt__SigningKey) map to configuration sections (Jwt:SigningKey). That one convention is what makes the same code run under user secrets on a laptop, environment variables in a container, and a key vault in the cloud.

Versioning before the first client

Once a client depends on your API, changing a response shape breaks them. Version from the start, when it costs nothing:

dotnet add package Asp.Versioning.Http
using Asp.Versioning;

builder.Services.AddApiVersioning(options =>
{
    options.DefaultApiVersion = new ApiVersion(1);
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.ReportApiVersions = true;
});
var versions = app.NewApiVersionSet()
    .HasApiVersion(new ApiVersion(1))
    .HasApiVersion(new ApiVersion(2))
    .ReportApiVersions()
    .Build();

var v1 = app.MapGroup("/api/v{version:apiVersion}").WithApiVersionSet(versions).MapToApiVersion(1);
v1.MapProductEndpoints();
v1.MapOrderEndpoints();

// v2 adds an Origin field to a single product endpoint to demonstrate side-by-side versions.
app.MapGroup("/api/v{version:apiVersion}").WithApiVersionSet(versions).MapToApiVersion(2)
   .MapProductEndpointsV2();

The versioned group now supplies the /api prefix, so the endpoint groups drop it: MapGroup("/api/products") becomes MapGroup("/products") and MapGroup("/api/orders") becomes MapGroup("/orders"). With that one-line change in each file, /api/products becomes /api/v1/products and the handlers themselves do not change. Any client that used the old URLs, including the integration tests, needs the /v1 added.

Every response now carries an api-supported-versions: 1, 2 header, which is how a client discovers that a newer version exists. The OpenAPI document is still a single document (there is one AddOpenApi() call), with the routes listed as /api/v{version}/....

The deployment landscape in five minutes

Target How When it fits
Azure Container Apps azd init then azd up; Aspire's manifest drives the provisioning Fastest path from AppHost to a URL
Kubernetes aspirate or the Aspire manifest to generate manifests/Helm You already run a cluster
Any container host The image from PublishContainer plus environment variables Everything else

The instructor plays a recorded azd up rather than running it live; conference Wi-Fi has ended more demos than bad code has. The recording shows the full flow from azd init to hitting the menu endpoint on a public URL, and the repo README has the commands.

Head to the lab

Lab 5: Run It Like Production