skip to content

ServiceDefaults Project

The ServiceDefaults project gives every service one AddServiceDefaults call that adds OpenTelemetry, health checks, service discovery and HttpClient resilience. Interviewers ask what it hides.

on this pageshow

explore

questions

4

In an Aspire solution, what does builder.AddServiceDefaults() turn on in each service, and why is ServiceDefaults a project rather than a package?

level: juniorimportance: must knowfreq 55%

answer

  1. one line in every service's Program.cs
  2. ConfigureOpenTelemetry plus AddDefaultHealthChecks
  3. AddServiceDiscovery on the service collection
  4. ConfigureHttpClientDefaults: resilience and discovery
  5. IsAspireSharedProject; you own Extensions.cs

basics

~20 s

AddServiceDefaults is a template-generated extension that adds OpenTelemetry logs, metrics and traces, a self liveness check, service discovery, and resilience plus discovery on every factory-created HttpClient. It ships as source in your solution so each team can edit it.

solid answer

~40 s

The `aspire-servicedefaults` template generates a class library whose `Extensions.cs` defines `AddServiceDefaults<TBuilder>()` on any `IHostApplicationBuilder`. It calls `ConfigureOpenTelemetry()` (OpenTelemetry logging, ASP.NET Core, HttpClient and runtime metrics, ASP.NET Core and HttpClient tracing, OTLP export when an endpoint is configured), `AddDefaultHealthChecks()` (a `self` check tagged `live`), `Services.AddServiceDiscovery()`, and `ConfigureHttpClientDefaults` so every factory client gets `AddStandardResilienceHandler()` and `AddServiceDiscovery()`. `MapDefaultEndpoints()` is a separate call after `Build()` that maps `/health` and `/alive`, only in Development. It is a project marked `IsAspireSharedProject` rather than a package because it is a starting point you are expected to change: add an instrumentation, restrict discovery schemes or expose health routes differently, and keep those choices in one place for all services.

code

csharp · 17 lines
csharp
var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();

builder.Services.AddProblemDetails();
builder.Services.AddHttpClient<RatingClient>(client =>
    client.BaseAddress = new("https+http://rating-engine"));

var app = builder.Build();

app.UseExceptionHandler();
app.MapPost("/quotes", (QuoteRequest request, RatingClient rating) =>
    rating.PriceAsync(request));

app.MapDefaultEndpoints();

app.Run();

go deeper

for a junior

Recall the four things AddServiceDefaults turns on and that MapDefaultEndpoints is a separate call after Build().

for a middle

Explain each call in Extensions.cs, why the method targets IHostApplicationBuilder, and why a worker can use it but cannot map the health routes.

for a senior

Show that you treat Extensions.cs as owned code: review what it exposes in production and keep edits deliberate across all services.

for a principal

Discuss whether a shared defaults project should become an internal package once many teams depend on it, and who owns its changes.

## Where ServiceDefaults comes from Every Aspire starter solution contains a project named something like `QuotePlatform.ServiceDefaults`, generated by the `aspire-servicedefaults` template. It is an ordinary class library on `Microsoft.NET.Sdk` with: - `<IsAspireSharedProject>true</IsAspireSharedProject>`, which tells Aspire tooling to reference it from projects it enlists in orchestration and to insert the `AddServiceDefaults()` call; - a `FrameworkReference` to `Microsoft.AspNetCore.App`; - package references to `Microsoft.Extensions.Http.Resilience`, `Microsoft.Extensions.ServiceDiscovery`, `OpenTelemetry.Exporter.OpenTelemetryProtocol`, `OpenTelemetry.Extensions.Hosting` and the ASP.NET Core, HTTP and runtime instrumentation packages; - one file, `Extensions.cs`, in the `Microsoft.Extensions.Hosting` namespace so the methods appear on builders without an extra `using`. For an insurance-quoting platform with five services (quotes API, rating engine, documents API, broker portal and an underwriting worker) each service references this one project and calls one line. ## What `AddServiceDefaults()` does | Call inside `AddServiceDefaults` | Effect | |---|---| | `ConfigureOpenTelemetry()` | OpenTelemetry logging with formatted messages and scopes; ASP.NET Core, HttpClient and runtime metrics; ASP.NET Core and HttpClient tracing plus an `ActivitySource` named after the application; OTLP export only if `OTEL_EXPORTER_OTLP_ENDPOINT` is set | | `AddDefaultHealthChecks()` | `AddHealthChecks().AddCheck("self", ...)` tagged `live`, always Healthy while the process responds | | `Services.AddServiceDiscovery()` | the resolver with the configuration and pass-through endpoint providers | | `Services.ConfigureHttpClientDefaults(...)` | every `IHttpClientFactory` client gets `AddStandardResilienceHandler()` and `AddServiceDiscovery()` | The method is generic, `AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder`, so it works on a `WebApplicationBuilder` and on the `HostApplicationBuilder` of a worker service alike. ## `MapDefaultEndpoints()` is separate Health routes need an HTTP pipeline, so they are mapped by a second method that extends `WebApplication` and is called after `Build()`: 1. `/health` runs every registered health check. 2. `/alive` runs only checks tagged `live`, which by default is just `self`. 3. Both are mapped **only when `app.Environment.IsDevelopment()`**, with a comment pointing at the security implications of exposing them elsewhere. The underwriting worker, built on `Host.CreateApplicationBuilder`, calls `AddServiceDefaults()` and gets telemetry, discovery and resilient clients, but it has no `WebApplication` to call `MapDefaultEndpoints()` on. ## Why it is a project, not a package The defaults are opinions, and Aspire hands them to you as source so that you own them: - the template leaves gRPC client instrumentation commented out, for teams that need it to enable; - it carries a commented `ServiceDiscoveryOptions` block for restricting discovery schemes; - teams routinely change health-route exposure, add exporters, or add their own `ActivitySource` names. A package would freeze those choices or force a configuration surface for each of them. A project keeps them as plain C# that code review can see, and it versions with the solution. The trade-off is that updating the package versions does not bring later template changes into an edited `Extensions.cs`; comparing it with a freshly generated template is a manual job. ## What it does not do - It does not register database clients or caches; those come from client integrations such as `AddNpgsqlDataSource`. - It does not inject configuration; the AppHost does that through environment variables, and any service can read them without this project. - It does not make a service appear in the AppHost; `AddProject` in the AppHost does. ## Adopting it in an existing solution A team that adds Aspire to the quoting platform after the fact follows the same steps for every service: 1. Create the project once with `dotnet new aspire-servicedefaults -o QuotePlatform.ServiceDefaults`. 2. Reference it from each service project. 3. Call `builder.AddServiceDefaults()` right after creating the builder, and `app.MapDefaultEndpoints()` before `app.Run()` in each web service. 4. Delete the hand-written setup it replaces: a second OpenTelemetry block, a second OTLP exporter, or a custom health check also named `self`. The last step matters more than it looks. Health check names must be unique: if a service already registered a check named `self`, `DefaultHealthCheckService` throws an `ArgumentException` listing the duplicate name when it is created. Duplicate telemetry wiring is quieter but just as real, typically doubling what a service exports or splitting its configuration across two places. ## What interviewers probe - Whether you know the defaults are source code, and have read them. - Whether you can say which piece belongs to ServiceDefaults and which to the AppHost: the AppHost injects addresses and settings, ServiceDefaults makes the service use them. - Whether you would keep the defaults identical across services, or let one service diverge and document why.

  • Can a service still run under the AppHost without calling AddServiceDefaults?
    Yes. The AppHost injects connection strings, service endpoints and OTLP settings as environment variables, and any app can read them. Without the defaults the service simply exports no telemetry to the dashboard, resolves no `https+http://` names through `HttpClient` and adds no resilience, unless it wires those itself.
  • Why does AddServiceDefaults use a generic TBuilder constrained to IHostApplicationBuilder?
    So one method serves web apps and worker services. `WebApplicationBuilder` and `HostApplicationBuilder` both implement `IHostApplicationBuilder`, which exposes `Services`, `Configuration`, `Logging` and `Environment`, everything the defaults touch, and the generic return keeps the caller's concrete builder type for chaining.

  • AddServiceDefaults is called once in the AppHost's AppHost.cs for all services.
  • ServiceDefaults is a NuGet package whose code you cannot change.
  • AddServiceDefaults also maps the /health and /alive endpoints.
  • Without AddServiceDefaults a service cannot read connection strings from the AppHost.
  • AddServiceDefaults only works in ASP.NET Core apps, never in worker services.
open as a page

In an Aspire service, how does an HttpClient whose BaseAddress is https+http://rating-engine reach a real address?

level: middleimportance: should knowfreq 46%

basics

~20 s

The service-discovery handler that ConfigureHttpClientDefaults adds rewrites the logical URI: it looks up rating-engine in the Services configuration the AppHost injected, prefers HTTPS endpoints, falls back to HTTP only when none exist, and picks one endpoint per request.

open as a page

In an Aspire ServiceDefaults project, why does MapDefaultEndpoints map /health and /alive only in Development, and what should change before production?

level: seniorimportance: should knowfreq 34%

basics

~20 s

The template wraps both MapHealthChecks calls in IsDevelopment() because public health routes have security implications. In Production they return 404, so probes that expect them fail until you map them deliberately, limited to an internal port or host.

open as a page

In an Aspire ServiceDefaults project, when does ConfigureOpenTelemetry actually export telemetry, and why might a service deployed without the AppHost export nothing?

level: seniorimportance: should knowfreq 33%

basics

~20 s

ConfigureOpenTelemetry always sets up logs, metrics and traces, but it registers the OTLP exporter only when OTEL_EXPORTER_OTLP_ENDPOINT has a value. The AppHost injects that variable; a deployment that does not set it collects telemetry and sends it nowhere.

open as a page