Community编程与开发github.com

Aspire配置

配置 Aspire AppHost 通过环境变量显式输出应用配置,使应用程序代码无需依赖 Aspire 客户端和服务发现。

Aspire配置 是什么?

该技能详细描述了如何在 Aspire 项目中配置 AppHost,以显式方式将资源输出(如数据库连接、存储服务 URL)映射为应用程序的环境变量或配置键。其核心原则是让 AppHost 拥有所有 Aspire 基础设施包,而应用程序本身只通过 `IOptions<T>` 或 `Configuration` 绑定配置,绝不引入 Aspire 客户端或服务发现依赖。这种做法确保了生产环境配置的透明性和可移植性——即使生产环境没有 Aspire,也能通过环境变量或配置文件完美复现。该技能适用于所有 Aspire 项目,包含清晰的配置流程、代码示例(AppHost 和应用程序两端)以及「应做/不应做」清单,帮助开发者保持架构解耦并简化集成测试。

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

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Aspire 配置

何时使用该技能

在以下情况下使用该技能:

  • 将 AppHost 资源连接到 Aspire 仓库中的应用配置时
  • 确保生产环境配置透明且可在 Aspire 之外移植时
  • 避免在应用程序代码内使用 Aspire 客户端/服务发现包时
  • 为开发/测试设计功能开关而不更改应用代码路径时

核心原则

  1. AppHost 拥有 Aspire 基础设施包

    • Aspire 托管包仅属于 AppHost。
    • 应用程序项目不应引用 Aspire 客户端/服务发现包。
  2. 仅使用显式配置

    • AppHost 必须将资源输出转换为显式配置键(环境变量)。
    • 应用程序代码仅绑定到 IOptions<T> 或 Configuration。
  3. 生产环境一致性和透明性

    • AppHost 注入的每个值都必须在生产环境中可表示为环境变量或配置文件,而无需 Aspire。
    • 避免不透明的服务发现和隐式配置。

配置流程

AppHost 资源 -> WithEnvironment(...) -> 应用配置键 -> 应用中的 IOptions<T>

AppHost 负责将 Aspire 资源转换为显式应用设置。 应用程序从不直接使用 Aspire 客户端或服务发现。


AppHost 模式(显式映射)

示例:数据库 + Blob 存储

// 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();

关键点

  • WithReference(db, "Postgres") 显式设置 ConnectionStrings__Postgres。
  • 每个外部依赖都通过显式配置键表示。
  • API 项目仅读取 Configuration 值。

应用程序代码模式(无 Aspire 客户端)

应用程序代码绑定到选项并直接初始化 SDK。它从不依赖 Aspire 客户端包或服务发现。

// 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); // 仅使用显式选项
});

不要在应用程序中添加 Aspire 客户端包(或 AddServiceDiscovery)。 这些是编排相关的问题,应保留在 AppHost 中。


功能开关和测试覆盖

将开关保留在配置中,并通过 AppHost 和测试夹具驱动它们。这可以保持开发/测试和生产环境配置之间的一致。

// AppHost:通过配置覆盖在测试中禁用持久化
var config = builder.Configuration.GetSection("App")
    .Get<AppHostConfiguration>() ?? new AppHostConfiguration();

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

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

有关将配置覆盖传递到 DistributedApplicationTestingBuilder 的模式,请参阅 skills/aspire/integration-testing/SKILL.md。


应做/不应做清单

应做

  • 将每个 Aspire 资源输出映射到显式配置键
  • 对所有基础设施设置使用带验证的 IOptions<T>
  • 将 AppHost 保持为唯一引用 Aspire 托管包的地方
  • 确保所有 AppHost 注入的值都可以在生产环境变量中设置

不应做

  • 在应用程序项目中引用 Aspire 客户端/服务发现包
  • 依赖无法在生产环境中镜像的不透明服务发现
  • 将配置隐藏在仅 Aspire 的抽象之后

相关技能

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

资源

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.

相关技能