.NET Aspire service defaults
Cloud-native applications often require extensive configurations to ensure they work across different environments reliably and securely. .NET Aspire provides many helper methods and tools to streamline the management of configurations for OpenTelemetry, health checks, environment variables, and more.
Explore the service defaults project
When you either Enlist in .NET Aspire orchestration or create a new .NET Aspire project, the YourAppName.ServiceDefaults project is added to your solution. For example, when building an API, you call the AddServiceDefaults method in the Program.cs file of your apps:
builder.AddServiceDefaults();
The AddServiceDefaults method handles the following concerns for you:
- Configures OpenTelemetry metrics and tracing.
- Add default health check endpoints.
- Add service discovery functionality.
- Configures HttpClient to work with service discovery.
For more information, see Provided extension methods for details on the AddServiceDefaults method.
Important
The .NET Aspire service defaults project is specifically designed for sharing the Extensions.cs file and its functionality. Please refrain from including other shared functionality or models in this project, use a conventional shared class library project for those purposes.
Project characteristics
The YourAppName.ServiceDefaults project is a .NET 8.0 library that contains the following XML:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAspireSharedProject>true</IsAspireSharedProject>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="8.3.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="8.0.0-preview.4.24156.9" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.7.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.7.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.7.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.GrpcNetClient" Version="1.7.0-beta.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.7.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Process" Version="0.5.0-beta.4" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.7.0" />
</ItemGroup>
</Project>
The IsAspireSharedProject property is set to true, which indicates that this project is a shared project. The .NET Aspire tooling uses this project as a reference for other projects added to a .NET Aspire solution. When you enlist the new project for orchestration, it automatically references the YourAppName.ServiceDefaults project and updates the Program.cs file to call the AddServiceDefaults method.
Provided extension methods
The YourAppName.ServiceDefaults project exposes a single Extensions.cs file that contains several opinionated extension methods:
AddServiceDefaults: Adds service defaults functionality.ConfigureOpenTelemetry: Configures OpenTelemetry metrics and tracing.AddDefaultHealthChecks: Adds default health check endpoints.MapDefaultEndpoints: Maps the health checks endpoint to/healthand the liveness endpoint to/alive.
Add service defaults functionality
The AddServiceDefaults method defines default configurations with the following opinionated functionality:
public static IHostApplicationBuilder AddServiceDefaults(
this IHostApplicationBuilder builder)
{
builder.ConfigureOpenTelemetry();
builder.AddDefaultHealthChecks();
builder.Services.AddServiceDiscovery();
builder.Services.ConfigureHttpClientDefaults(http =>
{
// Turn on resilience by default
http.AddStandardResilienceHandler();
// Turn on service discovery by default
http.UseServiceDiscovery();
});
return builder;
}
The preceding code:
- Configures OpenTelemetry metrics and tracing, by calling the
ConfigureOpenTelemetrymethod. - Adds default health check endpoints, by calling the
AddDefaultHealthChecksmethod. - Adds service discovery functionality, by calling the
AddServiceDiscoverymethod. - Configures HttpClient defaults, by calling the
ConfigureHttpClientDefaultsmethod—which is based on Build resilient HTTP apps: Key development patterns:- Adds the standard HTTP resilience handler, by calling the
AddStandardResilienceHandlermethod. - Specifies that the IHttpClientBuilder should use service discovery, by calling the
UseServiceDiscoverymethod.
- Adds the standard HTTP resilience handler, by calling the
- Returns the
IHostApplicationBuilderinstance to allow for method chaining.
OpenTelemetry configuration
Telemetry is a critical part of any cloud-native application. .NET Aspire provides a set of opinionated defaults for OpenTelemetry, which are configured with the ConfigureOpenTelemetry method:
public static IHostApplicationBuilder ConfigureOpenTelemetry(
this IHostApplicationBuilder builder)
{
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
});
builder.Services.AddOpenTelemetry()
.WithMetrics(metrics =>
{
metrics.AddRuntimeInstrumentation()
.AddBuiltInMeters();
})
.WithTracing(tracing =>
{
if (builder.Environment.IsDevelopment())
{
// We want to view all traces in development
tracing.SetSampler(new AlwaysOnSampler());
}
tracing.AddAspNetCoreInstrumentation()
.AddGrpcClientInstrumentation()
.AddHttpClientInstrumentation();
});
builder.AddOpenTelemetryExporters();
return builder;
}
The ConfigureOpenTelemetry method:
- Adds .NET Aspire telemetry logging to include formatted messages and scopes.
- Adds OpenTelemetry metrics and tracing that include:
- Runtime instrumentation metrics.
- Builtin meters.
- In a development environment, the
AlwaysOnSampleris used to view all traces. - Tracing details for ASP.NET Core, gRPC and HTTP instrumentation.
- Adds OpenTelemetry exporters, by calling
AddOpenTelemetryExporters.
The AddOpenTelemetryExporters method is defined privately as follows:
private static IHostApplicationBuilder AddOpenTelemetryExporters(
this IHostApplicationBuilder builder)
{
var useOtlpExporter = !string.IsNullOrWhiteSpace(
builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
if (useOtlpExporter)
{
builder.Services.Configure<OpenTelemetryLoggerOptions>(
logging => logging.AddOtlpExporter());
builder.Services.ConfigureOpenTelemetryMeterProvider(
metrics => metrics.AddOtlpExporter());
builder.Services.ConfigureOpenTelemetryTracerProvider(
tracing => tracing.AddOtlpExporter());
}
// Uncomment the following lines to enable the Prometheus exporter
// (requires the OpenTelemetry.Exporter.Prometheus.AspNetCore package)
// builder.Services.AddOpenTelemetry()
// .WithMetrics(metrics => metrics.AddPrometheusExporter());
// Uncomment the following lines to enable the Azure Monitor exporter
// (requires the Azure.Monitor.OpenTelemetry.Exporter package)
// builder.Services.AddOpenTelemetry()
// .UseAzureMonitor();
return builder;
}
The AddOpenTelemetryExporters method adds OpenTelemetry exporters based on the following conditions:
- If the
OTEL_EXPORTER_OTLP_ENDPOINTenvironment variable is set, the OpenTelemetry exporter is added. - Optionally consumers of .NET Aspire service defaults can uncomment some code to enable the Prometheus exporter, or the Azure Monitor exporter.
For more information, see .NET Aspire telemetry.
Health checks configuration
Health checks are used by various tools and systems to assess the readiness of your app. .NET Aspire provides a set of opinionated defaults for health checks, which are configured with the AddDefaultHealthChecks method:
public static IHostApplicationBuilder AddDefaultHealthChecks(
this IHostApplicationBuilder builder)
{
builder.Services.AddHealthChecks()
// Add a default liveness check to ensure app is responsive
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
return builder;
}
The AddDefaultHealthChecks method adds a default liveness check to ensure the app is responsive. The call to AddHealthChecks registers the HealthCheckService. For more information, see .NET Aspire health checks.
Web app health checks configuration
To expose health checks in a web app, .NET Aspire automatically determines the type of project being referenced within the solution, and adds the appropriate call to MapDefaultEndpoints:
public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
// Uncomment the following line to enable the Prometheus endpoint
// (requires the OpenTelemetry.Exporter.Prometheus.AspNetCore package)
// app.MapPrometheusScrapingEndpoint();
// All health checks must pass for app to be considered ready to
// accept traffic after starting
app.MapHealthChecks("/health");
// Only health checks tagged with the "live" tag must pass for app
// to be considered alive
app.MapHealthChecks("/alive", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live")
});
return app;
}
The MapDefaultEndpoints method:
- Allows consumers to optionally uncomment some code to enable the Prometheus endpoint.
- Maps the health checks endpoint to
/health. - Maps the liveness endpoint to
/aliveroute where the health check tag containslive.
For more information, see .NET Aspire health checks.
Next steps
This code is derived from the .NET Aspire Starter Application template and is intended as a starting point. You're free to modify this code however you deem necessary to meet your needs. It's important to know that service defaults project and its functionality are automatically applied to all project resources in a .NET Aspire solution.
.NET Aspire
Feedback
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback.
Submit and view feedback for