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 Annotations | 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("主機為必填");
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 |
| 可測試 | 驗證器是純類別 |