Community程式設計與開發github.com

aspire-configuration

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

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

name: aspire-configuration description: Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery. invocable: false

Aspire Configuration

When to Use This Skill

Use this skill when:

  • Wiring AppHost resources to application configuration in Aspire-based repos
  • Ensuring production configuration is transparent and portable outside of Aspire
  • Avoiding Aspire client/service-discovery packages inside application code
  • Designing feature toggles for dev/test without changing app code paths

Core Principles

  1. AppHost owns Aspire infrastructure packages

    • Aspire Hosting packages belong in AppHost only.
    • App projects should not reference Aspire client/service-discovery packages.
  2. Explicit configuration only

    • AppHost must translate resource outputs into explicit config keys (env vars).
    • App code binds to IOptions<T> or Configuration only.
  3. Production parity and transparency

    • Every value injected by AppHost must be representable in production as env vars or config files without Aspire.
    • Avoid opaque service discovery and implicit configuration.

Configuration Flow

AppHost resource -> WithEnvironment(...) -> app config keys -> IOptions<T> in app

The AppHost is responsible for turning Aspire resources into explicit app settings. The application never consumes Aspire clients or service discovery directly.


AppHost Patterns (Explicit Mapping)

Example: Database + Blob Storage

// AppHost/Program.cs
var builder = DistributedApplication.CreateBuilder(args);

var postgres = builder.AddPostgres("postgres");
var db = postgres.AddDatabase("appdb");

var minio = builder.AddContainer("minio", "minio/minio")
    .WithArgs("server", "/data")
    .WithHttpEndpoint(targetPort: 9000, name: "http")
    .WithHttpEndpoint(targetPort: 9001, name: "console")
    .WithEnvironment("MINIO_ROOT_USER", "minioadmin")
    .WithEnvironment("MINIO_ROOT_PASSWORD", "minioadmin");

var api = builder.AddProject<Projects.MyApp_Api>("api")
    .WithReference(db, "Postgres")
    .WithEnvironment("BlobStorage__Enabled", "true")
    .WithEnvironment("BlobStorage__ServiceUrl", minio.GetEndpoint("http"))
    .WithEnvironment("BlobStorage__AccessKey", "minioadmin")
    .WithEnvironment("BlobStorage__SecretKey", "minioadmin")
    .WithEnvironment("BlobStorage__Bucket", "attachments")
    .WithEnvironment("BlobStorage__ForcePathStyle", "true");

builder.Build().Run();

Key points

  • WithReference(db, "Postgres") sets ConnectionStrings__Postgres explicitly.
  • Every external dependency is represented via explicit config keys.
  • The API project only reads Configuration values.

App Code Pattern (No Aspire Clients)

Application code binds to options and initializes SDKs directly. It never depends on Aspire client packages or service discovery.

// Api/Program.cs
builder.Services
    .AddOptions<BlobStorageOptions>()
    .BindConfiguration("BlobStorage")
    .ValidateDataAnnotations()
    .ValidateOnStart();

builder.Services.AddSingleton<IBlobStorageService>(sp =>
{
    var options = sp.GetRequiredService<IOptions<BlobStorageOptions>>().Value;
    return new S3BlobStorageService(options); // uses explicit options only
});

Do not add Aspire client packages (or AddServiceDiscovery) to the app. Those are orchestration concerns and should stay in AppHost.


Feature Toggles and Test Overrides

Keep toggles in config and drive them through AppHost and test fixtures. This maintains parity between dev/test and production configuration.

// AppHost: disable persistence in tests via config overrides
var config = builder.Configuration.GetSection("App")
    .Get<AppHostConfiguration>() ?? new AppHostConfiguration();

if (!config.UseVolumes)
{
    postgres.WithDataVolume(false);
}

api.WithEnvironment("BlobStorage__Enabled", config.EnableBlobStorage.ToString());

See skills/aspire/integration-testing/SKILL.md for patterns on passing configuration overrides into DistributedApplicationTestingBuilder.


Do / Don’t Checklist

Do

  • Map every Aspire resource output to explicit configuration keys
  • Use IOptions<T> with validation for all infrastructure settings
  • Keep AppHost as the only place that references Aspire hosting packages
  • Ensure any AppHost-injected value can be set in production env vars

Don’t

  • Reference Aspire client/service-discovery packages in application projects
  • Rely on opaque service discovery that cannot be mirrored in production
  • Hide configuration behind Aspire-only abstractions

Related Skills

  • skills/aspire/service-defaults/SKILL.md
  • skills/aspire/integration-testing/SKILL.md
  • skills/akka/aspire-configuration/SKILL.md

Resources

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-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

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.

相關技能