Community程式設計與開發github.com

aspire-service-defaults

為Aspire應用程式建立共用的ServiceDefaults專案,集中管理所有服務的OpenTelemetry、健康檢查、復原能力與服務探索設定。

aspire-service-defaults 是什麼?

此技能用於建立一個共用的 ServiceDefaults 專案,專為 Aspire 架構的分散式應用程式設計。它將所有服務所需的通用配置(如 OpenTelemetry 的日誌、追蹤與指標、健康檢查端點、HTTP 用戶端復原能力與服務探索)集中管理,並透過 `AddServiceDefaults()` 方法讓每個服務輕鬆引用。支援 ASP.NET Core Web API 與背景工作服務,並整合至 Aspire AppHost 以自動設定 OTLP 匯出與端點。此技能可大幅減少重複設定程式碼,確保分散式應用程式的可觀測性與穩定性一致。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/aspire-service-defaults

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

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內建重試、斷路器、逾時
新增自訂追蹤來源擷取領域特定範圍

資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相關技能