跳到正文
cccskills
免费在 GitHub 公开

ioptions-pattern-migration

Migrate from manual configuration binding to ASP.NET Core IOptions pattern

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(1)

  • SKILL.md4.5 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Category: .NET Configuration
Complexity: Intermediate
Tags: #aspnetcore #ioptions #configuration #dependency-injection

When to Use

  • Migrating from manual config.Bind() + TryAddSingleton() pattern to ASP.NET Core IOptions
  • Adding configuration validation at startup
  • Improving testability of configuration-dependent services

Prerequisites

  • ASP.NET Core application with appsettings.json
  • Settings classes (POCOs) with properties matching config sections
  • Understanding of Dependency Injection

Steps

1. Update Program.cs Registration

Before:

var settings = new MySettings();
builder.Configuration.Bind("MySection", settings);
builder.Services.TryAddSingleton<IMySettings>(settings);

After:

builder.Services.Configure<MySettings>(builder.Configuration.GetSection("MySection"));
builder.Services.AddOptions<MySettings>()
    .ValidateDataAnnotations()
    .ValidateOnStart();

2. Update Consumer Constructors

Before:

public class MyService
{
    private readonly IMySettings _settings;
    
    public MyService(IMySettings settings)
    {
        _settings = settings;
    }
}

After:

using Microsoft.Extensions.Options;

public class MyService
{
    private readonly MySettings _settings;
    
    public MyService(IOptions<MySettings> settingsOptions)
    {
        _settings = settingsOptions.Value;
    }
}

3. Update Tests

Before:

var mockSettings = new Mock<IMySettings>();
mockSettings.Setup(s => s.Property).Returns("value");
var sut = new MyService(mockSettings.Object);

After:

using Microsoft.Extensions.Options;

var settings = new MySettings { Property = "value" };
var settingsOptions = Options.Create(settings);
var sut = new MyService(settingsOptions);

4. Add Validation (Optional but Recommended)

using System.ComponentModel.DataAnnotations;

public class MySettings
{
    [Required]
    [Url]
    public required string ApiBaseUrl { get; set; }
    
    [Range(1, 3600)]
    public int TimeoutSeconds { get; set; } = 30;
}

Common Pitfalls

❌ Don't: Use IOptions<T> in Razor Views

Razor views should inject IOptions<T> and unwrap in a code block:

@using Microsoft.Extensions.Options
@inject IOptions<Settings> SettingsOptions
@{
    var settings = SettingsOptions.Value;
}
<img src="@settings.StaticContentRootUrl/logo.png" />

❌ Don't: Call .Value in Constructor

If unwrapping in constructor, store the unwrapped value:

private readonly string _apiUrl;

public MyService(IOptions<Settings> options)
{
    _apiUrl = options.Value.ApiUrl;  // ✅ Unwrap once, store value
}

❌ Don't: Mix IOptions with Manual Binding

Pick one pattern per project for consistency.

When to Use IOptionsSnapshot

Use IOptionsSnapshot<T> instead of IOptions<T> if:

  • Configuration can reload during runtime
  • Service is scoped (not singleton)
  • Need per-request configuration values
builder.Services.AddScoped<IMyService, MyService>();

public MyService(IOptionsSnapshot<MySettings> settings) { }

Validation Options

1. Data Annotations (Recommended for Simple Cases)

builder.Services.AddOptions<MySettings>()
    .ValidateDataAnnotations()
    .ValidateOnStart();

2. Custom Validation

builder.Services.AddOptions<MySettings>()
    .Validate(settings => !string.IsNullOrWhiteSpace(settings.ApiKey), 
              "ApiKey must be provided")
    .ValidateOnStart();

3. IValidateOptions<T> (Complex Validation)

public class MySettingsValidator : IValidateOptions<MySettings>
{
    public ValidateOptionsResult Validate(string? name, MySettings options)
    {
        if (string.IsNullOrWhiteSpace(options.ApiKey))
            return ValidateOptionsResult.Fail("ApiKey is required");
        
        return ValidateOptionsResult.Success;
    }
}

builder.Services.AddSingleton<IValidateOptions<MySettings>, MySettingsValidator>();

Benefits

✅ Early validation (fail-fast at startup)
✅ Better testability (Options.Create() for tests)
✅ Standard ASP.NET Core pattern
✅ Supports config reloading (with IOptionsSnapshot)
✅ Type-safe configuration access

Related

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Standard collaboration patterns for all squad agents — worktree awareness, decisions, cross-agent communication

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Shared hard rules enforced across all squad agents

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Comprehensive AI prompt engineering safety review and improvement prompt. Analyzes prompts for safety, bias, security vulnerabilities, and effectiveness while providing detailed improvement recommendations with extensive frameworks, testing methodologies, and educational content.

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Migrate API controller scope checks to framework-enforced authorization policies while preserving ownership checks.

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Review API DTO implementations for contract/domain separation, mapping patterns, and REST compliance

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

Register shared claims transformation and hierarchical role policies in the API without breaking existing scope enforcement.

中文简介正在准备中。当前显示原文说明。

jguadagno/jjgnet-broadcast182026年8月4日 更新

查看 jguadagno 的全部技能

报告此技能的问题