Community编程与开发github.com

aspire-service-defaults

创建 Aspire 应用程序的共享 ServiceDefaults 项目。集中管理所有服务的 OpenTelemetry、健康检查、弹性策略和服务发现配置。

aspire-service-defaults 是什么?

此技能用于为 Aspire 分布式应用程序创建统一的 ServiceDefaults 共享项目。它集成了 OpenTelemetry(日志、追踪、指标)、健康检查(就绪和存活端点)、服务发现(自动解析服务地址)以及 HTTP 弹性策略(重试和断路器)。使用此技能可以确保所有服务在可观测性、可靠性和服务间通信上保持一致,减少重复配置。它支持包括 Web API 和 Worker 服务在内的所有 Aspire 项目类型,并能自动与 Aspire Dashboard 集成以发送遥测数据。开发者只需在每个服务中引用 ServiceDefaults 项目并调用 `AddServiceDefaults()` 方法即可。

兼容平台~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 等),则使用 OTLP 导出器
        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();

Worker 服务

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.

相关技能