Community编程与开发github.com

Microsoft.Extensions 配置模式

使用 Microsoft.Extensions.Options 模式,包括 IValidateOptions、强类型设置、启动时验证以及 Options 模式,进行整洁的配置管理。

Microsoft.Extensions 配置模式 是什么?

此技能涵盖了 Microsoft.Extensions.Options 库中用于在 .NET 应用程序中实现强类型配置的完整模式和实践。它从基本绑定开始,介绍如何使用数据注释进行验证,然后深入介绍更高级的 IValidateOptions<T> 接口,该接口支持跨属性验证、条件检查以及依赖注入。该技能强调了在启动时进行验证(`.ValidateOnStart()`)以快速失败的重要性,而非在运行时因配置错误而失败。它还解释了 `IOptions<T>`、`IOptionsSnapshot<T>` 和 `IOptionsMonitor<T>` 之间的生命周期差异,展示了如何响应配置更改(尤其在后台服务中)。此外,还介绍了后配置(PostConfigure)以在验证前修改选项。该技能适用于所有主要的 .NET 平台(ASP.NET Core、Worker Services、控制台应用、MAUI)。通过遵循此处描述的模式,开发人员可以避免常见的反模式(如绕过验证或直接访问 `IConfiguration`),并构建出包含清晰验证规则、可测试且易于维护的配置类。

兼容平台~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:数据注释验证

对于简单的验证规则,请使用数据注释:

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;
}

启用数据注释验证

builder.Services.AddOptions<SmtpSettings>()
    .BindConfiguration(SmtpSettings.SectionName)
    .ValidateDataAnnotations()  // 启用基于属性的验证
    .ValidateOnStart();         // 在启动时立即验证

关键点: .ValidateOnStart() 至关重要。没有它,验证仅在首次访问选项时运行。


模式 3:用于复杂验证的 IValidateOptions

数据注释适用于简单规则,但复杂验证需要 IValidateOptions<T>:

场景数据注释IValidateOptions
必填字段是是
范围检查是是
跨属性验证否是
条件验证否是
外部服务检查否是
验证器中的依赖注入否是

实现 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("Host 是必需的");

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

顺序很重要: 数据注释先运行,然后是 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("Required 缺失"); // 太晚了!
    }
}

// 良好:通过 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 类
简单验证数据注释
复杂验证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.

相关技能