配置系统(Configuration)就是国家级枢纽的制度手册、参数中心和环境差异来源。
ASP.NET Core 会把多个来源的配置合并起来,常见来源有:
appsettings.jsonappsettings.{Environment}.json- 环境变量
- 命令行参数
- 开发期机密存储
#示例:appsettings.json
{
"HubOptions": {
"CityName": "星港市",
"MaxDailyAppointments": 2000,
"EnableSelfServiceKiosk": true
}
}#读取配置
builder.Services.Configure<HubOptions>(
builder.Configuration.GetSection("HubOptions"));
public class HubOptions
{
public string CityName { get; set; } = "";
public int MaxDailyAppointments { get; set; }
public bool EnableSelfServiceKiosk { get; set; }
}using Microsoft.Extensions.Options;
public class AppointmentService : IAppointmentService
{
private readonly HubOptions _options;
public AppointmentService(IOptions<HubOptions> options)
{
_options = options.Value;
}
}#为什么配置不能写死在代码里
因为“是否开启自助机”“数据库地址是什么”“日志级别如何”这些都不是代码逻辑本身,而是枢纽运营参数。
代码 = 枢纽怎么运转
配置 = 枢纽今天按什么规则运转这两者混在一起,系统就会越来越僵硬。