选项模式在 ASP.NET Core 中使用类来提供对相关配置设置的强类型访问。通过将配置设置隔离到单独的类,应用程序遵循封装和关注点分离的原则。封装确保依赖于配置的类仅依赖于其使用的设置;关注点分离则确保应用的不同部分的设置互不依赖或耦合。此外,选项模式还提供了验证配置数据的机制。
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<Setting>().BindConfiguration("Setting");
var app = builder.Build();
app.Services.GetService<IOptionsMonitor<Setting>>()?.OnChange((setting, name) =>
{
app.Logger.LogInformation(setting.Value);
});
app.MapGet("/opt1", (IOptions option) =>
{
app.Logger.LogInformation("opt1");
return option.Value;
});
app.MapGet("/opt2", (IOptionsSnapshot option) =>
{
app.Logger.LogInformation("opt2");
return option.Value;
});
app.MapGet("/opt3", (IOptionsMonitor option) =>
{
app.Logger.LogInformation("opt3");
return option.CurrentValue;
});
app.Run();
class Setting
{
public string Name { get; set; }
public string Value { get; set; }
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Setting": {
"Name": "key",
"Value": "1234567890"
}
}
@OptionDemo_HostAddress = http://localhost:5064
GET {{OptionDemo_HostAddress}}/opt1
Accept: application/json
###
GET {{OptionDemo_HostAddress}}/opt2
Accept: application/json
###
GET {{OptionDemo_HostAddress}}/opt3
Accept: application/json
###
打开OptionDemo.http,点击Opt1,Opt2,Opt3的“发送请求”,结果如下:
把 appsettings.json中的Setting的Value改成“1234567890ABCD”,结果如下:
可以通过Validate()方法对Options进行验证,目前有两种验证点,一个是服务启动时,即有ValidateOnStart方法;另外一种是在使用这个Options时,即不写ValidateOnStart方法。