Atvik
Mar 17, 9 PM - Mar 21, 10 AM
Taktu þátt í fundarröðinni til að byggja upp skalanlegar gervigreindarlausnir byggðar á raunverulegum notkunartilvikum með öðrum forriturum og sérfræðingum.
Nýskrá núnaÞessi vafri er ekki lengur studdur.
Uppfærðu í Microsoft Edge til að nýta þér nýjustu eiginleika, öryggisuppfærslur og tæknilega aðstoð.
In this article, you learn about the .NET Aspire service defaults project, a set of extension methods that:
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.
When you either Enlist in .NET Aspire orchestration or create a new .NET Aspire project, the YourAppName.ServiceDefaults.csproj 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 tasks:
For more information, see Provided extension methods for details on the AddServiceDefaults
method.
Mikilvægt
The .NET Aspire service defaults project is specifically designed for sharing the Extensions.cs file and its functionality. Don't include other shared functionality or models in this project. Use a conventional shared class library project for those purposes.
The YourAppName.ServiceDefaults project is a .NET 9.0 library that contains the following XML:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.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="9.2.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.1.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.11.2" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.11.2" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.11.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.11.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.11.0" />
</ItemGroup>
</Project>
The service defaults project template imposes a FrameworkReference
dependency on Microsoft.AspNetCore.App
.
Ábending
If you don't want to take a dependency on Microsoft.AspNetCore.App
, you can create a custom service defaults project. For more information, see Custom service defaults.
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.
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 /health
and the liveness endpoint to /alive
.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.AddServiceDiscovery();
});
// Uncomment the following to restrict the allowed schemes for service discovery.
// builder.Services.Configure<ServiceDiscoveryOptions>(options =>
// {
// options.AllowedSchemes = ["https"];
// });
return builder;
}
The preceding code:
ConfigureOpenTelemetry
method.AddDefaultHealthChecks
method.AddServiceDiscovery
method.ConfigureHttpClientDefaults
method—which is based on Build resilient HTTP apps: Key development patterns:
AddStandardResilienceHandler
method.UseServiceDiscovery
method.IHostApplicationBuilder
instance to allow for method chaining.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.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation();
})
.WithTracing(tracing =>
{
if (builder.Environment.IsDevelopment())
{
// We want to view all traces in development
tracing.SetSampler(new AlwaysOnSampler());
}
tracing.AddAspNetCoreInstrumentation()
// Uncomment the following line to enable gRPC instrumentation
// (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
//.AddGrpcClientInstrumentation()
.AddHttpClientInstrumentation();
});
builder.AddOpenTelemetryExporters();
return builder;
}
The ConfigureOpenTelemetry
method:
AlwaysOnSampler
is used to view all traces.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.AspNetCore package)
//if (!string.IsNullOrEmpty(
// builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
//{
// builder.Services.AddOpenTelemetry()
// .UseAzureMonitor();
//}
return builder;
}
The AddOpenTelemetryExporters
method adds OpenTelemetry exporters based on the following conditions:
OTEL_EXPORTER_OTLP_ENDPOINT
environment variable is set, the OpenTelemetry exporter is added.For more information, see .NET Aspire telemetry.
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.
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();
// Adding health checks endpoints to applications in non-development
// environments has security implications.
// See https://aka.ms/dotnet/aspire/healthchecks for details before
// enabling these endpoints in non-development environments.
if (app.Environment.IsDevelopment())
{
// 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:
/health
./alive
route where the health check tag contains live
.For more information, see .NET Aspire health checks.
If the default service configuration provided by the project template is not sufficient for your needs, you have the option to create your own service defaults project. This is especially useful when your consuming project, such as a Worker project or WinForms project, cannot or does not want to have a FrameworkReference
dependency on Microsoft.AspNetCore.App
.
To do this, create a new .NET 9.0 class library project and add the necessary dependencies to the project file, consider the following example:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" />
</ItemGroup>
</Project>
Then create an extensions class that contains the necessary methods to configure the app defaults:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
namespace Microsoft.Extensions.Hosting;
public static class AppDefaultsExtensions
{
public static IHostApplicationBuilder AddAppDefaults(
this IHostApplicationBuilder builder)
{
builder.ConfigureAppOpenTelemetry();
builder.Services.AddServiceDiscovery();
builder.Services.ConfigureHttpClientDefaults(http =>
{
// Turn on resilience by default
http.AddStandardResilienceHandler();
// Turn on service discovery by default
http.AddServiceDiscovery();
});
return builder;
}
public static IHostApplicationBuilder ConfigureAppOpenTelemetry(
this IHostApplicationBuilder builder)
{
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
});
builder.Services.AddOpenTelemetry()
.WithMetrics(static metrics =>
{
metrics.AddRuntimeInstrumentation();
})
.WithTracing(tracing =>
{
if (builder.Environment.IsDevelopment())
{
// We want to view all traces in development
tracing.SetSampler(new AlwaysOnSampler());
}
tracing.AddGrpcClientInstrumentation()
.AddHttpClientInstrumentation();
});
builder.AddOpenTelemetryExporters();
return builder;
}
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());
}
return builder;
}
}
This is only an example, and you can customize the AppDefaultsExtensions
class to meet your specific needs.
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 umsögn
.NET Aspire er opið verkefni. Veldu tengil til að gefa umsögn:
Atvik
Mar 17, 9 PM - Mar 21, 10 AM
Taktu þátt í fundarröðinni til að byggja upp skalanlegar gervigreindarlausnir byggðar á raunverulegum notkunartilvikum með öðrum forriturum og sérfræðingum.
Nýskrá núna