Communityコーディング&開発github.com

aspire-service-defaults

Aspireアプリケーション向けの共有ServiceDefaultsプロジェクトを作成します。全サービスでOpenTelemetry、ヘルスチェック、レジリエンス、サービスディスカバリの設定を一元化します。

aspire-service-defaults とは?

このスキルは、.NET Aspireベースの分散アプリケーションにおいて、全サービスで共通の構成を提供する共有ライブラリ「ServiceDefaults」プロジェクトを作成・管理するためのものです。開発者はこのスキルを使用することで、OpenTelemetry(ログ、トレース、メトリクス)、HTTPレジリエンス(リトライ、サーキットブレーカー)、ヘルスチェック(死活監視および準備態勢確認)、サービスディスカバリ(自動アドレス解決)を一貫して設定できます。主要なプラットフォームとしては、.NET Aspire SDK(特に.NET 9)、OpenTelemetry .NET SDK、Microsoft.Extensions.Http.Resilienceライブラリ、およびMicrosoft.Extensions.ServiceDiscoveryをサポートしています。スキルは`AddServiceDefaults()`拡張メソッドを呼び出すだけで、すべてのサービスが共通のテレメトリーエクスポート(OTLP)、ヘルスチェックエンドポイント(`/health`、`/alive`)、標準レジリエンスハンドラー、カスタムトレースソースの追加機能を利用できるようになります。また、開発環境と本番環境でヘルスチェックの公開方法を切り替えたり、データベースやRedisなどの外部依存関係に対するカスタムヘルスチェックを追加するためのベストプラクティスも提供します。

対応~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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Aspire Service Defaults

このスキルを使用するタイミング

以下の場合にこのスキルを使用します:

  • Aspireベースの分散アプリケーションを構築する場合
  • サービス全体で一貫した可観測性(ログ、トレース、メトリクス)が必要な場合
  • 共有のヘルスチェック構成が必要な場合
  • HttpClientのレジリエンスとサービスディスカバリを構成する場合

ServiceDefaultsとは

ServiceDefaultsは、Aspireアプリケーション内のすべてのサービスに共通の設定を提供する共有プロジェクトです:

  • OpenTelemetry - ログ、トレース、メトリクス
  • ヘルスチェック - 死活監視(liveness)と準備態勢確認(readiness)エンドポイント
  • サービスディスカバリ - 自動サービス解決
  • 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エンドポイントが設定されている場合、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();

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またはカスタムのActivitySourcesの場合:

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プロジェクトは1つ全サービスで一貫した設定
ヘルスチェックをトレースからフィルタリング可観測性データのノイズを削減
ヘルスチェックにタグを付ける死活監視と準備態勢確認を分離
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.

関連スキル