aspire-service-defaults

Crée un projet ServiceDefaults partagé pour les applications Aspire. Centralise la configuration d'OpenTelemetry, des health checks, de la résilience et de la découverte de services pour tous les services.

Qu'est-ce que aspire-service-defaults ?

Cette compétence permet de créer et configurer un projet partagé `ServiceDefaults` pour les applications .NET Aspire. Elle centralise la configuration commune de tous les microservices : OpenTelemetry (logging, tracing, métriques), les health checks (readiness et liveness), la découverte de services et les politiques de résilience HTTP (retry, circuit breaker). Le projet génère les fichiers nécessaires (Extensions.cs, .csproj) et montre comment les intégrer dans les services API, Worker et l'AppHost. La configuration filtre les health checks des traces OpenTelemetry pour réduire le bruit, et utilise automatiquement l'exportateur OTLP si l'endpoint est configuré. Cette approche garantit une observabilité et une résilience cohérentes à travers tous les services de l'application distribuée.

Compatible avec~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/aspire-service-defaults

Installed? Explore more Développement et programmation skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Valeurs par défaut des services Aspire

Quand utiliser cette compétence

Utilisez cette compétence quand :

  • Vous construisez des applications distribuées basées sur Aspire
  • Vous avez besoin d'une observabilité cohérente (logging, tracing, métriques) entre les services
  • Vous voulez une configuration partagée des health checks
  • Vous configurez la résilience HttpClient et la découverte de services

Qu'est-ce que ServiceDefaults ?

ServiceDefaults est un projet partagé qui fournit une configuration commune pour tous les services d'une application Aspire :

  • OpenTelemetry - Logging, tracing et métriques
  • Health Checks - Points de terminaison readiness et liveness
  • Service Discovery - Résolution automatique des services
  • Résilience HTTP - Stratégies de retry et circuit breaker

Chaque service référence ce projet et appelle AddServiceDefaults().


Structure du projet

src/
  MyApp.ServiceDefaults/
    Extensions.cs
    MyApp.ServiceDefaults.csproj
  MyApp.Api/
    Program.cs  # Appelle AddServiceDefaults()
  MyApp.Worker/
    Program.cs  # Appelle AddServiceDefaults()
  MyApp.AppHost/
    Program.cs

Projet ServiceDefaults

Fichier projet

<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>
    /// Ajoute les services Aspire communs : OpenTelemetry, health checks,
    /// découverte de services et résilience HTTP.
    /// </summary>
    public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder)
        where TBuilder : IHostApplicationBuilder
    {
        builder.ConfigureOpenTelemetry();
        builder.AddDefaultHealthChecks();

        builder.Services.AddServiceDiscovery();

        builder.Services.ConfigureHttpClientDefaults(http =>
        {
            // Résilience : retries, circuit breaker, timeouts
            http.AddStandardResilienceHandler();

            // Découverte de services : résoudre les noms de services en adresses
            http.AddServiceDiscovery();
        });

        return builder;
    }

    public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder)
        where TBuilder : IHostApplicationBuilder
    {
        // Logging
        builder.Logging.AddOpenTelemetry(logging =>
        {
            logging.IncludeFormattedMessage = true;
            logging.IncludeScopes = true;
        });

        builder.Services.AddOpenTelemetry()
            // Métriques
            .WithMetrics(metrics =>
            {
                metrics
                    .AddAspNetCoreInstrumentation()
                    .AddHttpClientInstrumentation()
                    .AddRuntimeInstrumentation();
            })
            // Tracing
            .WithTracing(tracing =>
            {
                tracing
                    .AddSource(builder.Environment.ApplicationName)
                    .AddAspNetCoreInstrumentation(options =>
                        // Exclure les health checks des traces
                        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
    {
        // Utiliser l'exportateur OTLP si l'endpoint est configuré (Tableau de bord Aspire, Jaeger, etc.)
        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>
    /// Mappe les points de terminaison des health checks. À appeler après UseRouting().
    /// </summary>
    public static WebApplication MapDefaultEndpoints(this WebApplication app)
    {
        // Exposer uniquement en développement - voir la note de sécurité ci-dessous
        if (app.Environment.IsDevelopment())
        {
            // Readiness : tous les health checks doivent réussir
            app.MapHealthChecks(HealthEndpointPath);

            // Liveness : uniquement les checks tagués "live"
            app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions
            {
                Predicate = r => r.Tags.Contains("live")
            });
        }

        return app;
    }
}

Utilisation dans les services

Service API

var builder = WebApplication.CreateBuilder(args);

// Ajouter toutes les valeurs par défaut des services
builder.AddServiceDefaults();

// Ajouter vos services
builder.Services.AddControllers();

var app = builder.Build();

// Mapper les points de terminaison de santé
app.MapDefaultEndpoints();

app.MapControllers();
app.Run();

Service Worker

var builder = Host.CreateApplicationBuilder(args);

// Fonctionne aussi pour les hôtes non-web
builder.AddServiceDefaults();

builder.Services.AddHostedService<MyWorker>();

var host = builder.Build();
host.Run();

Ajout de health checks personnalisés

public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder)
    where TBuilder : IHostApplicationBuilder
{
    builder.Services.AddHealthChecks()
        // Liveness basique
        .AddCheck("self", () => HealthCheckResult.Healthy(), ["live"])

        // Readiness base de données
        .AddNpgSql(
            builder.Configuration.GetConnectionString("postgres")!,
            name: "postgres",
            tags: ["ready"])

        // Readiness Redis
        .AddRedis(
            builder.Configuration.GetConnectionString("redis")!,
            name: "redis",
            tags: ["ready"])

        // Check personnalisé
        .AddCheck<MyCustomHealthCheck>("custom", tags: ["ready"]);

    return builder;
}

Ajout de sources de traces personnalisées

Pour Akka.NET ou des ActivitySources personnalisés :

public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder)
    where TBuilder : IHostApplicationBuilder
{
    builder.Services.AddOpenTelemetry()
        .WithTracing(tracing =>
        {
            tracing
                .AddSource(builder.Environment.ApplicationName)
                // Tracing Akka.NET
                .AddSource("Akka.NET")
                // Sources personnalisées
                .AddSource("MyApp.Orders")
                .AddSource("MyApp.Payments")
                .AddAspNetCoreInstrumentation()
                .AddHttpClientInstrumentation();
        });

    return builder;
}

Health checks en production

En production, protégez les points de terminaison de santé ou utilisez des chemins différents :

public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
    // Toujours mapper pour les sondes Kubernetes, mais envisagez :
    // - Utiliser des ports internes uniquement
    // - Ajouter une autorisation
    // - Limiter le débit

    app.MapHealthChecks("/health", new HealthCheckOptions
    {
        // Ne retourner que le statut, pas les détails
        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;
}

Intégration avec AppHost

L'AppHost configure automatiquement les points de terminaison 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();

Les services reçoivent automatiquement OTEL_EXPORTER_OTLP_ENDPOINT, envoyant la télémétrie au tableau de bord Aspire.


Bonnes pratiques

PratiqueRaison
Un seul projet ServiceDefaultsConfiguration cohérente sur tous les services
Filtrer les health checks des tracesRéduit le bruit dans les données d'observabilité
Tagger les health checksSéparer liveness de readiness
Utiliser StandardResilienceHandlerRetry, circuit breaker, timeout intégrés
Ajouter des sources de traces personnaliséesCapturer des spans spécifiques au domaine

Ressources

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.

Skills associés