aspire-service-defaults

Cria um projeto ServiceDefaults compartilhado para aplicações Aspire. Centraliza a configuração de OpenTelemetry, health checks, resiliência e descoberta de serviços entre todos os serviços.

O que é aspire-service-defaults?

Esta habilidade cria um projeto compartilhado chamado ServiceDefaults que fornece configuração padronizada para todos os serviços em uma aplicação distribuída Aspire. Ela centraliza a configuração de OpenTelemetry (logging, tracing e métricas), health checks (prontidão e atividade), resiliência de HttpClient (retry, circuit breaker e timeouts) e descoberta de serviços. O ServiceDefaults é referenciado por cada serviço, que chama o método `AddServiceDefaults()` para aplicar todas as configurações automaticamente. A habilidade cobre desde a criação do projeto, configuração de dependências NuGet, código de extensão em C#, até o mapeamento de endpoints de health check e a integração com o AppHost, garantindo telemetria consistente via OTLP. É útil para desenvolvedores .NET que constroem aplicações baseadas em Aspire e buscam reduzir duplicação de configuração, melhorar observabilidade e aplicar práticas recomendadas de resiliência. A implementação inclui dicas de segurança para produção, como proteger endpoints de health check e filtrar traces para evitar ruído.

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

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Aspire Service Defaults

Quando Usar Esta Habilidade

Use esta habilidade quando:

  • Estiver construindo aplicações distribuídas baseadas em Aspire
  • Precisar de observabilidade consistente (logging, tracing, métricas) entre serviços
  • Quiser configuração de health checks compartilhada
  • Estiver configurando resiliência de HttpClient e descoberta de serviços

O que é ServiceDefaults?

ServiceDefaults é um projeto compartilhado que fornece configuração comum para todos os serviços em uma aplicação Aspire:

  • OpenTelemetry - Logging, tracing e métricas
  • Health Checks - Endpoints de prontidão e atividade
  • Descoberta de Serviços - Resolução automática de serviços
  • Resiliência HTTP - Políticas de retry e circuit breaker

Cada serviço referencia este projeto e chama AddServiceDefaults().


Estrutura do Projeto

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

Projeto ServiceDefaults

Arquivo do Projeto

<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>
    /// Adiciona serviços Aspire comuns: OpenTelemetry, health checks,
    /// descoberta de serviços e resiliência HTTP.
    /// </summary>
    public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder)
        where TBuilder : IHostApplicationBuilder
    {
        builder.ConfigureOpenTelemetry();
        builder.AddDefaultHealthChecks();

        builder.Services.AddServiceDiscovery();

        builder.Services.ConfigureHttpClientDefaults(http =>
        {
            // Resiliência: retries, circuit breaker, timeouts
            http.AddStandardResilienceHandler();

            // Descoberta de serviços: resolve nomes de serviços para endereços
            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étricas
            .WithMetrics(metrics =>
            {
                metrics
                    .AddAspNetCoreInstrumentation()
                    .AddHttpClientInstrumentation()
                    .AddRuntimeInstrumentation();
            })
            // Tracing
            .WithTracing(tracing =>
            {
                tracing
                    .AddSource(builder.Environment.ApplicationName)
                    .AddAspNetCoreInstrumentation(options =>
                        // Exclui health checks dos 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
    {
        // Usa o exportador OTLP se o endpoint estiver configurado (Aspire Dashboard, 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>
    /// Mapeia endpoints de health check. Chamar após UseRouting().
    /// </summary>
    public static WebApplication MapDefaultEndpoints(this WebApplication app)
    {
        // Expõe apenas em desenvolvimento - veja nota de segurança abaixo
        if (app.Environment.IsDevelopment())
        {
            // Prontidão: todos os health checks devem passar
            app.MapHealthChecks(HealthEndpointPath);

            // Atividade: apenas checks marcados com "live"
            app.MapHealthChecks(AlivenessEndpointPath, new HealthCheckOptions
            {
                Predicate = r => r.Tags.Contains("live")
            });
        }

        return app;
    }
}

Uso nos Serviços

Serviço de API

var builder = WebApplication.CreateBuilder(args);

// Adiciona todos os defaults do serviço
builder.AddServiceDefaults();

// Adiciona seus serviços
builder.Services.AddControllers();

var app = builder.Build();

// Mapeia endpoints de health
app.MapDefaultEndpoints();

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

Serviço Worker

var builder = Host.CreateApplicationBuilder(args);

// Funciona também para hosts não-web
builder.AddServiceDefaults();

builder.Services.AddHostedService<MyWorker>();

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

Adicionando Health Checks Personalizados

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

        // Prontidão do banco de dados
        .AddNpgSql(
            builder.Configuration.GetConnectionString("postgres")!,
            name: "postgres",
            tags: ["ready"])

        // Prontidão do Redis
        .AddRedis(
            builder.Configuration.GetConnectionString("redis")!,
            name: "redis",
            tags: ["ready"])

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

    return builder;
}

Adicionando Fontes de Trace Personalizadas

Para Akka.NET ou ActivitySources personalizados:

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

    return builder;
}

Health Checks em Produção

Para produção, proteja os endpoints de health ou use caminhos diferentes:

public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
    // Sempre mapear para probes do Kubernetes, mas considere:
    // - Usar portas apenas internas
    // - Adicionar autorização
    // - Limitação de taxa

    app.MapHealthChecks("/health", new HealthCheckOptions
    {
        // Retorna apenas status, não detalhes
        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;
}

Integração com AppHost

O AppHost configura automaticamente os endpoints 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();

Os serviços recebem OTEL_EXPORTER_OTLP_ENDPOINT automaticamente, enviando telemetria para o Aspire Dashboard.


Melhores Práticas

PráticaMotivo
Um único projeto ServiceDefaultsConfiguração consistente em todos os serviços
Filtrar health checks dos tracesReduz ruído nos dados de observabilidade
Taggear health checksSeparar atividade de prontidão
Usar StandardResilienceHandlerRetry, circuit breaker e timeout embutidos
Adicionar fontes de trace personalizadasCapturar spans específicos do domínio

Recursos

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.

Habilidades Relacionadas