Lab 5: Run It Like Production
30 minutes on the schedule, closer to 40 if you do every step · Starts from checkpoint-4 · Ends at checkpoint-5 (the finished Roastery API)
Steps 1 and 2 need only the SDK, the Aspire templates, and the Aspire CLI. Step 3 needs Docker or Podman. Step 4 needs nothing extra.
warning Short on time?
Do Steps 1 and 2 first; they are the point of the module. If the day is running long, cut in the same order as the schedule: skip Step 4 (versioning) first, then Step 3 (container), which the instructor will demo. When you run out of time, git checkout checkpoint-5 gets you the finished API with everything below already done.
Step 1: Add the Aspire projects
Install the Aspire project templates once, if you did not already do it during setup:
dotnet new install Aspire.ProjectTemplates
Then, from the src folder:
dotnet new aspire-apphost -n Roastery.AppHost
dotnet new aspire-servicedefaults -n Roastery.ServiceDefaults
dotnet sln add Roastery.AppHost Roastery.ServiceDefaults
cd Roastery.AppHost
dotnet add reference ../Roastery.Api ../Roastery.Payments
cd ../Roastery.Api
dotnet add reference ../Roastery.ServiceDefaults
cd ../Roastery.Payments
dotnet add reference ../Roastery.ServiceDefaults
Replace the AppHost's AppHost.cs with the version on the concepts page. Keep the .WaitFor(payments) line: it stops the API starting before the payment service is up. Keep the .WithEnvironment("Payments__BaseUrl", …) line too; the next part explains it.
note
Building and running the AppHost requires the Aspire CLI (the dashboard and orchestrator bundle). If dotnet run on the AppHost complains it cannot resolve the Aspire bundle, install the CLI from get.aspire.dev and re-run. The API, tests, and container build in the other steps do not need it.
Wire up ServiceDefaults. In both the API and the payments project, add builder.AddServiceDefaults(); immediately after CreateBuilder, and app.MapDefaultEndpoints(); near the other Map calls. Then, in the API's Program.cs:
- Delete the
builder.AddRoasteryTelemetry();call.ServiceDefaultsnow configures OpenTelemetry, and calling both registers the instrumentation twice. You can also deleteObservability/Telemetry.cs; if you do, delete theusing Roastery.Api.Observability;line too. (The checkpoint leaves the file in place, unused.) - Delete the two
MapHealthCheckslines from Lab 4.MapDefaultEndpoints()maps/healthand/alivefor you. - Keep the
AddDbContextCheck<RoasteryDbContext>()registration.ServiceDefaultsadds the endpoints and aselfliveness check, not your database check.
Point the payment client at the service name. Change the fallback in the PaymentClient registration from "https://localhost:7281" to "https+http://payments":
builder.Services.AddHttpClient<PaymentClient>(client =>
client.BaseAddress = new Uri(builder.Configuration["Payments:BaseUrl"] ?? "https+http://payments"));
This snippet already drops the .AddStandardResilienceHandler() call; the next paragraph explains why.
payments is the resource name from the AppHost. The https+http:// scheme is service-discovery syntax for "use the HTTPS endpoint if the service has one, otherwise HTTP"; the resolver swaps in the real address that the AppHost injected as services__payments__https__0.
warning Why the AppHost sets Payments__BaseUrl
The ?? only falls through when Payments:BaseUrl is not set, and appsettings.json still sets it to https://localhost:7281 so the API keeps running on its own. Left alone, that value would win under Aspire too, and the API would call localhost:7281 directly without ever using discovery. It would even appear to work, because Aspire happens to start payments on that port.
The AppHost's .WithEnvironment("Payments__BaseUrl", "https+http://payments") fixes that. Environment variables override appsettings.json, so under the AppHost the configured address becomes the service name and discovery resolves it. Run standalone, the API still uses appsettings.json; in a container, Step 3 sets the variable to a real URL.
Remove the duplicate resilience handler. The ServiceDefaults template calls ConfigureHttpClientDefaults(http => http.AddStandardResilienceHandler()), which gives every HttpClient a resilience pipeline. The .AddStandardResilienceHandler() from Lab 4 on PaymentClient adds a second pipeline inside the first. Now every retry from the outer pipeline runs the inner pipeline's retries too, and the timeouts nest. Delete the .AddStandardResilienceHandler() on the PaymentClient registration so only the default applies. The checkpoint does exactly that.
Step 2: Run it and read the trace
Set Roastery.AppHost as the startup project and run it, or from the repo root:
dotnet run --project src/Roastery.AppHost
# or, with the Aspire CLI:
cd src/Roastery.AppHost && aspire run
The dashboard opens in the browser. If it does not, or it asks you to log in, copy the login URL from the console output (it looks like https://localhost:17xxx/login?t=...). The ?t= token is what signs you in.
note Files the Aspire CLI creates
aspire run may create aspire.config.json in the AppHost folder, which records which project is the AppHost. Commit it. It may also create a .aspire/ folder holding a local bundle, which you should not commit; add .aspire/ to .gitignore (the checkpoint already does this).
- Confirm both
apiandpaymentsshow Running. Click each resource's endpoint and browse to/health; both should returnHealthy. - Open
module-5.http. Set@baseUrlto theapiaddress shown in the dashboard (usually stillhttps://localhost:7181). Until you finish Step 4, the routes are not versioned yet, so change@api = {{baseUrl}}/api/v1to@api = {{baseUrl}}/apifor now, and skip thev2request at the bottom. Get a staff token and a customer token, then place an order as the customer. - Open Traces and find
POST /api/orders. Expand it and find the outboundHttpClientcall topaymentsand thePOST /chargespan from the payment service under it, which is the cross-service trace you came for. The fake provider fails about 30% of charges, so place a few more orders until you catch one where thepaymentscall shows several attempts: that is the resilience handler retrying. - Advance the order to
Roasting, thenReady, as staff. Open Structured logs, filter toapi, and find theOrderReadyNotifierentry,Order {OrderId} is ready; notifying {Email}.
You will not see EF Core query spans in the trace. ServiceDefaults registers ASP.NET Core and HttpClient instrumentation only; EF Core instrumentation is a separate package (see the stretch goals).
Step 3: Build and run the container
From the repo root:
dotnet publish src/Roastery.Api -c Release --os linux /t:PublishContainer -p:ContainerRepository=roastery-api
docker images roastery-api
Leaving out --arch builds for your machine's architecture, so on Apple Silicon you get an arm64 image that runs natively. Add --arch x64 only when the image is headed for an x64 host; forcing x64 on an ARM Mac runs it under emulation.
Run it with configuration supplied as environment variables. The container cannot reach the Aspire-hosted payments service by name, so point it at the host instead. Start the standalone payments service in another terminal first (dotnet run --project src/Roastery.Payments --launch-profile https):
docker run --rm -p 8080:8080 \
-e ASPNETCORE_ENVIRONMENT=Development \
-e ConnectionStrings__Roastery="Data Source=/tmp/roastery.db" \
-e Jwt__SigningKey="roastery-dev-signing-key-change-me-32-bytes" \
-e Payments__BaseUrl="https://host.docker.internal:7281" \
roastery-api
Why each variable is there:
ASPNETCORE_ENVIRONMENT=Development: the database migration and seed only run in Development, andMapDefaultEndpoints()only maps/healthand/alivein Development. Without it you get an empty database with no tables, and the health endpoints return 404.ConnectionStrings__Roastery: the image runs as the non-rootappuser, which cannot write to the app folder, so the defaultData Source=roastery.dbfails./tmpis writable. The database disappears with the container, which is fine for this step.Payments__BaseUrl: the samePayments:BaseUrlkey the code reads, with__standing in for:.
warning Linux hosts
host.docker.internal resolves automatically on Docker Desktop (macOS, Windows). On Linux, add --add-host=host.docker.internal:host-gateway to the docker run command.
Browse to http://localhost:8080/api/v1/products, or http://localhost:8080/api/products if you skipped Step 4. It is the same code, the same configuration keys, and a different environment.
Only the menu is expected to work. Placing an order calls payments over HTTPS on the host, and the development certificate is issued for localhost, not host.docker.internal, and is not trusted inside the container anyway. The charge fails with a TLS error. Making that work means a real certificate or running both services in containers, which is what Aspire and azd do for you.
tip
docker inspect roastery-api --format '{{.Config.User}} {{.Config.ExposedPorts}}' shows the user the SDK chose and the exposed port: 1654 map[8080/tcp:{}]. 1654 is the UID of the non-root app user built into the .NET images. Neither required a line of Dockerfile.
Step 4: Version the API
cd src/Roastery.Api && dotnet add package Asp.Versioning.Http
Add the AddApiVersioning registration and the version set from the concepts page (using Asp.Versioning; at the top of Program.cs). Then move the endpoints under the versioned group. That takes two changes, or every URL ends up as /api/v1/api/products:
- Shorten the group prefixes. In
ProductEndpoints.cs, changeapp.MapGroup("/api/products")toapp.MapGroup("/products"). InOrderEndpoints.cs, changeapp.MapGroup("/api/orders")toapp.MapGroup("/orders"). - Map them under
v1. InProgram.cs, replace theapp.MapProductEndpoints();andapp.MapOrderEndpoints();calls with thev1group from the concepts page.
Leave the /api/auth group alone; token endpoints are not versioned.
Now add one v2 endpoint: GET /api/v2/products/{id} returns the v1 product fields plus an Origin string. Create Endpoints/ProductEndpointsV2.cs:
using Microsoft.AspNetCore.Http.HttpResults;
using Roastery.Api.Contracts;
using Roastery.Api.Services;
namespace Roastery.Api.Endpoints;
public record ProductDtoV2(int Id, string Name, string Roast, decimal Price, bool InStock, string Origin);
public static class ProductEndpointsV2
{
public static IEndpointRouteBuilder MapProductEndpointsV2(this IEndpointRouteBuilder app)
{
app.MapGroup("/products").WithTags("Products")
.MapGet("/{id:int}", GetProductV2).WithName("GetProductV2");
return app;
}
static async Task<Results<Ok<ProductDtoV2>, NotFound>> GetProductV2(
int id, IProductCatalog catalog, CancellationToken ct)
{
var product = await catalog.FindAsync(id, ct);
if (product is null) return TypedResults.NotFound();
var dto = product.ToDto();
// v2 adds a (placeholder) Origin field; the roast name derives a plausible origin.
var origin = product.Name.Split(' ').FirstOrDefault() ?? "Unknown";
return TypedResults.Ok(new ProductDtoV2(dto.Id, dto.Name, dto.Roast, dto.Price, dto.InStock, origin));
}
}
Map it in Program.cs right after the v1 group, using the same version set:
// 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();
In module-5.http, set @api back to {{baseUrl}}/api/v1. Then check:
GET {{api}}/productsreturns200with anapi-supported-versions: 1, 2response header.GET {{baseUrl}}/api/v2/products/1returns the product with anoriginfield ("Ethiopia"for product 1).GET {{api}}/products/1returns the same product withoutorigin.- The old
GET /api/productsnow returns404.
Scalar still shows a single OpenAPI document; there is one AddOpenApi() call, so both versions' routes appear in it as /api/v{version}/.... Separate per-version documents are a stretch goal.
Fix the tests. The integration tests still call the unversioned URLs. In Roastery.Tests/OrderApiTests.cs, change the four request paths to /api/v1/products, /api/v1/orders/1/status (twice), and /api/v1/orders/2/status, then run dotnet test.
Stretch goals
- Prove discovery is doing the work. Change
Payments:BaseUrlin the API'sappsettings.jsonto a port nothing listens on, such ashttps://localhost:7999, then run under the AppHost. Orders still charge, because the AppHost's value replaces it. Run the API standalone and the same orders fail. - See EF Core in the trace. Add the
OpenTelemetry.Instrumentation.EntityFrameworkCorepackage to the API (it is prerelease, sodotnet add package OpenTelemetry.Instrumentation.EntityFrameworkCore --prerelease) and register it withbuilder.Services.AddOpenTelemetry().WithTracing(t => t.AddEntityFrameworkCoreInstrumentation());. Your queries then show up as spans under each request. - Link the notifier to the request. The
OrderReadyNotifierlog entry has its own trace, not thePUT's, because nothing carries the trace context through theChannel. Add anActivityContexttoOrderReadyMessage, captureActivity.Current?.Contextwhen you write the message, and in the notifier start anActivitywith it as the parent from anActivitySourcenamedRoastery.Api(the nameServiceDefaultsalready listens to). - Replace SQLite with Postgres:
builder.AddPostgres("db").AddDatabase("roastery")in the AppHost,.WithReference(db)on the API, theNpgsqlEF Core provider, and a fresh migration. Note how little of the API changed. - Deploy:
azd initin thesrcfolder, choose the AppHost, thenazd up. Requires an Azure subscription and about ten minutes. - Add the Aspire Redis resource and switch
HybridCacheto use it as the L2 withAddRedisDistributedCache("cache").
Common pitfalls
dotnet new aspire-apphostsays no templates match. Rundotnet new install Aspire.ProjectTemplatesfirst.- Health endpoints 404 under Aspire.
MapDefaultEndpoints()is missing. If/healthreturns but reports nothing about the database, you deleted theAddDbContextCheckregistration along with the oldMapHealthCheckslines. paymentsdoes not resolve.AddServiceDefaults()is not called in the API (it registers service discovery), orWithReference(payments)is missing in the AppHost. If orders charge under Aspire only whileappsettings.jsonhas the right port, the.WithEnvironment("Payments__BaseUrl", …)line is missing andappsettings.jsonis winning (discovery resolves to the samelocalhost:7281, so the trace alone will not tell you).- Far more retry spans than expected. Both
ServiceDefaultsand yourPaymentClientregistration add a standard resilience handler. Remove the per-client one. - Container exits on start, or every request fails. Read
docker logs.SQLite Error 14: unable to open database filemeans the connection string points somewhere theappuser cannot write; use/tmp.no such tablemeansASPNETCORE_ENVIRONMENT=Developmentis missing, so migrations did not run. /healthreturns 404 in the container. Same cause:MapDefaultEndpoints()only maps health endpoints in Development.- Every URL is
/api/v1/api/products. You moved the groups under the versioned group without shorteningMapGroup("/api/products")andMapGroup("/api/orders"). - Versioned routes 404. The route template must be
/api/v{version:apiVersion}exactly, and the group needsWithApiVersionSet.
Checkpoint
git add -A && git commit -m "Lab 5 complete"
# or: git checkout checkpoint-5
That is the finished Roastery API. Head to the Wrap-up.