Aspire Service Defaults
使用時機
在以下情況使用此技能:
- 建置基於 Aspire 的分散式應用程式
- 需要在所有服務間保持一致的可觀測性(記錄、追蹤、指標)
- 想要共用健康檢查設定
- 設定 HttpClient 復原能力與服務探索
什麼是 ServiceDefaults?
ServiceDefaults 是一個共用專案,為 Aspire 應用程式中的所有服務提供通用設定:
- OpenTelemetry – 記錄、追蹤與指標
- 健康檢查 – 就緒性與存活端點
- 服務探索 – 自動服務解析
- HTTP 復原能力 – 重試與斷路器原則
每個服務都會參考此專案並呼叫 AddServiceDefaults()。
專案結構
src/
MyApp.ServiceDefaults/
Extensions.cs
MyApp.ServiceDefaults.csproj
MyApp.Api/
Program.cs # 呼叫 AddServiceDefaults()
MyApp.Worker/
Program.cs # 呼叫 AddServiceDefaults()
MyApp.AppHost/
Program.cs
ServiceDefaults 專案
專案檔
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<IsAspireSharedProject>true</IsAspireSharedProject>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" />
</ItemGroup>
</Project>
Extensions.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
namespace Microsoft.Extensions.Hosting;
public static class Extensions
{
private const string HealthEndpointPath = "/health";
private const string AlivenessEndpointPath = "/alive";
/// <summary>
/// 新增常見的 Aspire 服務:OpenTelemetry、健康檢查、服務探索及 HTTP 復原能力。
/// </summary>
public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder)
where TBuilder : IHostApplicationBuilder
{
builder.ConfigureOpenTelemetry();
builder.AddDefaultHealthChecks();
builder.Services.AddServiceDiscovery();
builder.Services.ConfigureHttpClientDefaults(http =>
{
// 復原能力:重試、斷路器、逾時
http.AddStandardResilienceHandler();
// 服務探索:將服務名稱解析為位址
http.AddServiceDiscovery();
});
return builder;
}
public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder)
where TBuilder : IHostApplicationBuilder
{
// 記錄
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
});
builder.Services.AddOpenTelemetry()
// 指標
.WithMetrics(metrics =>
{
metrics
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation();
})
// 追蹤
.WithTracing(tracing =>
{
tracing
.AddSource(builder.Environment.ApplicationName)
.AddAspNetCoreInstrumentation(options =>
// 從追蹤中排除健康檢查
options.Filter = context =>
!context.Request.Path.StartsWithSegments(HealthEndpointPath) &&
!context.Request.Path.StartsWithSegments(AlivenessEndpointPath))
.AddHttpClientInstrumentation();
});
builder.AddOpenTelemetryExporters();
return builder;
}
private static TBuilder AddOpenTelemetryExporters<TBuilder>(this TBuilder builder)
where TBuilder : IHostApplicationBuilder
{
// 若有設定端點,則使用 OTLP 匯出器(Aspire Dashboard、Jaeger 等)
var useOtlp = !string.IsNullOrWhiteSpace(
builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
if (useOtlp)
{
builder.Services.AddOpenTelemetry().UseOtlpExporter();
}
return builder;
}
public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder)
where TBuilder : IHostApplicationBuilder
{
builder.Services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
return builder;
}
/// <summary>
/// 對應健康檢查端點。請在 UseRouting() 之後呼叫。
/// </summary>
public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
// 僅在開發環境下暴露(請參閱下方安全性注意事項)
if (app.Environment.IsDevelopment())
{
// 就緒性:必須通過所有健康檢查
app.MapHealthChecks(HealthEndpointPath);
// 存活:僅檢查標記為 "live" 的項目
app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live")
});
}
return app;
}
}
在服務中使用
API 服務
var builder = WebApplication.CreateBuilder(args);
// 新增所有服務預設值
builder.AddServiceDefaults();
// 新增您的服務
builder.Services.AddControllers();
var app = builder.Build();
// 對應健康檢查端點
app.MapDefaultEndpoints();
app.MapControllers();
app.Run();
背景工作服務
var builder = Host.CreateApplicationBuilder(args);
// 也適用於非 Web 主機
builder.AddServiceDefaults();
builder.Services.AddHostedService<MyWorker>();
var host = builder.Build();
host.Run();
新增自訂健康檢查
public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder)
where TBuilder : IHostApplicationBuilder
{
builder.Services.AddHealthChecks()
// 基本存活檢查
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"])
// 資料庫就緒性檢查
.AddNpgSql(
builder.Configuration.GetConnectionString("postgres")!,
name: "postgres",
tags: ["ready"])
// Redis 就緒性檢查
.AddRedis(
builder.Configuration.GetConnectionString("redis")!,
name: "redis",
tags: ["ready"])
// 自訂檢查
.AddCheck<MyCustomHealthCheck>("custom", tags: ["ready"]);
return builder;
}
新增自訂追蹤來源
適用於 Akka.NET 或自訂的 ActivitySource:
public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder)
where TBuilder : IHostApplicationBuilder
{
builder.Services.AddOpenTelemetry()
.WithTracing(tracing =>
{
tracing
.AddSource(builder.Environment.ApplicationName)
// Akka.NET 追蹤
.AddSource("Akka.NET")
// 自訂來源
.AddSource("MyApp.Orders")
.AddSource("MyApp.Payments")
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation();
});
return builder;
}
生產環境健康檢查
在生產環境中,請保護健康檢查端點或使用不同的路徑:
public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
// 始終為 Kubernetes 探測器對應端點,但請考慮:
// - 使用僅限內部的連接埠
// - 加入授權
// - 速率限制
app.MapHealthChecks("/health", new HealthCheckOptions
{
// 僅回傳狀態,不包含詳細資訊
ResponseWriter = (context, report) =>
{
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync(report.Status.ToString());
}
});
app.MapHealthChecks("/alive", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live"),
ResponseWriter = (context, report) =>
{
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync(report.Status.ToString());
}
});
return app;
}
與 AppHost 整合
AppHost 會自動設定 OTLP 端點:
// AppHost/Program.cs
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");
var redis = builder.AddRedis("redis");
var api = builder.AddProject<Projects.MyApp_Api>("api")
.WithReference(postgres)
.WithReference(redis);
builder.Build().Run();
服務會自動接收 OTEL_EXPORTER_OTLP_ENDPOINT,並將遙測資料傳送至 Aspire Dashboard。
最佳做法
| 做法 | 原因 |
|---|---|
| 一個 ServiceDefaults 專案 | 所有服務間的設定保持一致 |
| 從追蹤中過濾健康檢查 | 減少可觀測性資料中的雜訊 |
| 標記健康檢查 | 區分存活與就緒性檢查 |
| 使用 StandardResilienceHandler | 內建重試、斷路器、逾時 |
| 新增自訂追蹤來源 | 擷取領域特定範圍 |
資源
- Aspire Service Defaults:https://learn.microsoft.com/zh-tw/dotnet/aspire/fundamentals/service-defaults
- OpenTelemetry .NET:https://opentelemetry.io/docs/languages/net/
- 健康檢查:https://learn.microsoft.com/zh-tw/aspnet/core/host-and-deploy/health-checks