Community程式設計與開發github.com

microsoft-extensions-configuration

Microsoft.Extensions.Options 模式,包含 IValidateOptions、強型別設定、啟動時驗證以及 Options 模式,實現乾淨的設定管理。

microsoft-extensions-configuration 是什麼?

這個技能涵蓋了使用 Microsoft.Extensions.Options 進行 .NET 設定管理的模式與最佳實踐。它專注於「快速失敗」的哲學:在應用程式啟動時立即驗證所有設定,而不是在執行時期因為無效的設定而崩潰。技能詳細說明了五種主要模式:基本的選項繫結、使用 Data Annotations 進行簡單驗證、使用 IValidateOptions<T> 介面進行複雜的跨屬性與條件式驗證、使用 IOptionsSnapshot<T> 和 IOptionsMonitor<T> 處理選項的生命週期,以及用於修改已繫結選項的 PostConfigure 模式。它也明確指出了常見的反模式,例如手動存取 IConfiguration 而不進行驗證、在建構函式中進行驗證,或是忘記呼叫 ValidateOnStart()。使用者可以學會如何定義強型別的設定類別、將它們繫結到 appsettings.json,並註冊能夠注入依賴項的驗證器。這個技能支援在 .NET Core 與 .NET 5+ 應用程式中使用,適用於 Web API、背景服務以及任何依賴 IOptions 模式的專案。它推薦參考 advanced-patterns.md 以取得更進階的案例,例如具備相依性的驗證器和具名選項。

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

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Microsoft.Extensions 設定模式

何時使用此技能

在以下情況使用此技能:

  • 將 appsettings.json 的設定繫結到強型別類別
  • 在應用程式啟動時驗證設定(快速失敗)
  • 為設定實作複雜的驗證邏輯
  • 設計可測試且可維護的設定類別
  • 理解 IOptions、IOptionsSnapshot 與 IOptionsMonitor

參考檔案

  • advanced-patterns.md:具備相依性的驗證器、具名選項、完整的生產環境範例(AkkaSettings)以及測試驗證器

為什麼設定驗證很重要

問題: 應用程式常常因為設定錯誤而在執行時期失敗——缺少的連線字串、無效的 URL、超出範圍的值。這些失敗發生在商務邏輯的深處,遠離設定載入的地方。

解決方案: 在啟動時驗證設定。如果設定無效,立即失敗並顯示清晰的錯誤訊息。

// 不好:在執行時期,當有人嘗試使用服務時失敗
public class EmailService
{
    public EmailService(IOptions<SmtpSettings> options)
    {
        var settings = options.Value;
        // 在正式環境運作 10 分鐘後擲出 NullReferenceException
        _client = new SmtpClient(settings.Host, settings.Port);
    }
}

// 良好:在啟動時失敗,並顯示清晰錯誤
// "SmtpSettings 驗證失敗:Host 為必填"

模式 1:基本選項繫結

定義設定類別

public class SmtpSettings
{
    public const string SectionName = "Smtp";

    public string Host { get; set; } = string.Empty;
    public int Port { get; set; } = 587;
    public string? Username { get; set; }
    public string? Password { get; set; }
    public bool UseSsl { get; set; } = true;
}

從設定檔繫結

builder.Services.AddOptions<SmtpSettings>()
    .BindConfiguration(SmtpSettings.SectionName);

// appsettings.json
{
  "Smtp": {
    "Host": "smtp.example.com",
    "Port": 587,
    "Username": "[email protected]",
    "Password": "secret",
    "UseSsl": true
  }
}

在服務中使用

public class EmailService
{
    private readonly SmtpSettings _settings;

    // IOptions<T> - 單例,啟動時讀取一次
    public EmailService(IOptions<SmtpSettings> options)
    {
        _settings = options.Value;
    }
}

模式 2:Data Annotations 驗證

對於簡單的驗證規則,請使用 Data Annotations:

using System.ComponentModel.DataAnnotations;

public class SmtpSettings
{
    public const string SectionName = "Smtp";

    [Required(ErrorMessage = "SMTP 主機為必填")]
    public string Host { get; set; } = string.Empty;

    [Range(1, 65535, ErrorMessage = "連接埠必須介於 1 到 65535 之間")]
    public int Port { get; set; } = 587;

    [EmailAddress(ErrorMessage = "使用者名稱必須是有效的電子郵件地址")]
    public string? Username { get; set; }

    public string? Password { get; set; }
    public bool UseSsl { get; set; } = true;
}

啟用 Data Annotations 驗證

builder.Services.AddOptions<SmtpSettings>()
    .BindConfiguration(SmtpSettings.SectionName)
    .ValidateDataAnnotations()  // 啟用屬性型驗證
    .ValidateOnStart();         // 在啟動時立即驗證

關鍵點: .ValidateOnStart() 至關重要。沒有它,驗證只會在首次存取選項時執行。


模式 3:用於複雜驗證的 IValidateOptions

Data Annotations 適用於簡單規則,但複雜驗證需要 IValidateOptions<T>:

情境Data AnnotationsIValidateOptions
必填欄位是是
範圍檢查是是
跨屬性驗證否是
條件式驗證否是
外部服務檢查否是
驗證器中的依賴項注入否是

實作 IValidateOptions

using Microsoft.Extensions.Options;

public class SmtpSettingsValidator : IValidateOptions<SmtpSettings>
{
    public ValidateOptionsResult Validate(string? name, SmtpSettings options)
    {
        var failures = new List<string>();

        if (string.IsNullOrWhiteSpace(options.Host))
            failures.Add("主機為必填");

        if (options.Port is < 1 or > 65535)
            failures.Add($"連接埠 {options.Port} 無效。必須介於 1 到 65535 之間");

        // 跨屬性驗證
        if (!string.IsNullOrEmpty(options.Username) && string.IsNullOrEmpty(options.Password))
            failures.Add("當指定使用者名稱時,密碼為必填");

        // 條件式驗證
        if (options.UseSsl && options.Port == 25)
            failures.Add("連接埠 25 通常不與 SSL 一起使用。請考慮連接埠 465 或 587");

        return failures.Count > 0
            ? ValidateOptionsResult.Fail(failures)
            : ValidateOptionsResult.Success;
    }
}

註冊驗證器

builder.Services.AddOptions<SmtpSettings>()
    .BindConfiguration(SmtpSettings.SectionName)
    .ValidateDataAnnotations()
    .ValidateOnStart();

builder.Services.AddSingleton<IValidateOptions<SmtpSettings>, SmtpSettingsValidator>();

順序很重要: Data Annotations 會先執行,然後才是 IValidateOptions 驗證器。所有失敗訊息會被收集在一起。

請參閱 advanced-patterns.md 以了解具備相依性的驗證器、具名選項以及完整的生產環境範例。


模式 4:選項生命週期

介面生命週期是否隨變更重新載入使用案例
IOptions<T>單例否靜態設定,讀取一次
IOptionsSnapshot<T>範圍是(每次要求)需要最新設定的 Web 應用程式
IOptionsMonitor<T>單例是(含回呼)背景服務,即時更新

用於背景服務的 IOptionsMonitor

public class BackgroundWorker : BackgroundService
{
    private readonly IOptionsMonitor<WorkerSettings> _optionsMonitor;
    private WorkerSettings _currentSettings;

    public BackgroundWorker(IOptionsMonitor<WorkerSettings> optionsMonitor)
    {
        _optionsMonitor = optionsMonitor;
        _currentSettings = optionsMonitor.CurrentValue;

        _optionsMonitor.OnChange(settings =>
        {
            _currentSettings = settings;
        });
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await DoWorkAsync();
            await Task.Delay(_currentSettings.PollingInterval, stoppingToken);
        }
    }
}

模式 5:後續設定

在繫結之後、驗證之前修改選項:

builder.Services.AddOptions<ApiSettings>()
    .BindConfiguration("Api")
    .PostConfigure(options =>
    {
        if (!string.IsNullOrEmpty(options.BaseUrl) && !options.BaseUrl.EndsWith('/'))
            options.BaseUrl += '/';

        options.Timeout ??= TimeSpan.FromSeconds(30);
    })
    .ValidateDataAnnotations()
    .ValidateOnStart();

應避免的反模式

1. 手動存取設定

// 不好:繞過驗證,難以測試
public class MyService
{
    public MyService(IConfiguration configuration)
    {
        var host = configuration["Smtp:Host"]; // 沒有驗證!
    }
}

// 良好:強型別,已驗證
public class MyService
{
    public MyService(IOptions<SmtpSettings> options)
    {
        var host = options.Value.Host; // 在啟動時已驗證
    }
}

2. 在建構函式中驗證

// 不好:驗證發生在執行時期,而非啟動時
public class MyService
{
    public MyService(IOptions<Settings> options)
    {
        if (string.IsNullOrEmpty(options.Value.Required))
            throw new ArgumentException("缺少必填項目"); // 太晚了!
    }
}

// 良好:透過 IValidateOptions + ValidateOnStart() 在啟動時驗證

3. 忘記 ValidateOnStart

// 不好:驗證只在首次存取時執行
builder.Services.AddOptions<Settings>()
    .ValidateDataAnnotations(); // 缺少 ValidateOnStart!

// 良好:如果無效則立即失敗
builder.Services.AddOptions<Settings>()
    .ValidateDataAnnotations()
    .ValidateOnStart();

4. 在 IValidateOptions 中擲出例外

// 不好:擲出例外,中斷驗證鏈
public ValidateOptionsResult Validate(string? name, Settings options)
{
    if (options.Value < 0)
        throw new ArgumentException("數值不能為負"); // 錯誤!
    return ValidateOptionsResult.Success;
}

// 良好:回傳失敗結果
public ValidateOptionsResult Validate(string? name, Settings options)
{
    if (options.Value < 0)
        return ValidateOptionsResult.Fail("數值不能為負");
    return ValidateOptionsResult.Success;
}

總結

原則實作方式
快速失敗.ValidateOnStart()
強型別繫結到 POCO 類別
簡單驗證Data Annotations
複雜驗證IValidateOptions<T>
跨屬性規則IValidateOptions<T>
環境感知注入 IHostEnvironment
可測試驗證器是純類別

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

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.

相關技能