Community程式設計與開發github.com

aspire-configuration

設定 Aspire AppHost 透過環境變數明確輸出應用程式設定,讓應用程式程式碼不受 Aspire 用戶端和服務探索的限制。

aspire-configuration 是什麼?

此技能專門為使用 .NET Aspire 的開發者設計,目標是確保應用程式程式碼保持乾淨、可攜帶,且不直接依賴 Aspire 基礎架構套件或服務探索。其核心原則是讓 AppHost 專案負責承載所有 Aspire 基礎架構相關套件,並將所有資源輸出(如資料庫連線字串、物件儲存端點)明確轉換為應用程式的設定鍵(即環境變數)。應用程式本身僅透過標準的 `IOptions<T>` 或 `Configuration` API 來繫結這些設定,實現與生產環境的組態對等。它支援明確的組態對應模式,例如透過 `WithEnvironment` 和 `WithReference` 方法設定連線字串與功能切換。此外,它也提供在測試中覆寫設定的模式,確保開發、測試和生產環境的組態行為一致。這樣的做法避免了在應用程式程式碼中引入 Aspire 特定的抽象層,從而提升了程式碼的可移植性和維護性。

相容平台✓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 設定

使用時機

在以下情況使用此技能:

  • 在基於 Aspire 的儲存庫中,將 AppHost 資源連接到應用程式設定
  • 確保生產環境設定透明且可在 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.

相關技能