第一步 :新建ASP.NET Core webapi項目
第二步:安裝Microsoft.Extensions.Options和Microsoft.Extensions.Configuration.Binder
第三步:修改appsettings.json,內容如下:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"DB": {
"DbType": "SQLServer",
"Connection": "Data Source = .Catalog=DemoDB; Integrated Security = true"
},
"Smtp": {
"Server": "smtp.youzack.com",
"UserName": "zack",
"Password": "hello888",
},
"AllowedHosts": "*"
}
第四步:由于我們只讀取配置系統中“DB”和“Smtp”這兩部分,建立對應的模型類,代碼如下:
public class DbSettings
{
public string? DbType { get; set; }
public string? ConnectionString { get; set; }
}
public class SmtpSettings
{
public string? Server { get; set; }
public string? UserName { get; set; }
public string? Password { get; set; }
}
由于使用選項方式讀取配置的時候,需要和依賴注入一起使用,因此我們需要創建一個類用于獲取注入的選項值。聲明接收選項注入的對象的類型不能直接使用DbSettings、SmtpSettings,而要使用IOptions
、IOptionsMonitor 、IOptionsSnapshot 等泛型接口類型,因為它們可以幫我們處理容器生命周期、配置刷新等。它們的區別在于,IOptions 在配置改變后,我們不能讀到新的值,必須重啟程序才可以讀到新的值;IOptionsMonitor 在配置改變后,我們能讀到新的值;IOptionsSnapshot 也是在配置改變后,我們能讀到新的值,和IOptionsMonitor 不同的是,在同一個范圍內IOptionsMonitor 會保持一致性。
編寫讀取配置的Demo代碼 如下:
public class Demo
{
private readonly IOptionsSnapshot<DbSettings> optDbsettings;
private readonly IOptionsSnapshot<SmtpSettings> optSmtpSettings;
public Demo(IOptionsSnapshot<DbSettings> optDbsettings, IOptionsSnapshot<SmtpSettings> optSmtpSettings)
{
this.optDbsettings = optDbsettings;
this.optSmtpSettings = optSmtpSettings;
}
public void Test()
{
var db = optDbsettings.Value;
Console.WriteLine($"數據庫:{db.DbType},{db.ConnectionString}");
var smtp = optSmtpSettings.Value;
Console.WriteLine($"smtp:{smtp.Server},{smtp.UserName},{smtp.Password}");
}
}
注冊服務到容器
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfigurationRoot config = configurationBuilder.Build();
ServiceCollection services = new ServiceCollection();
services.AddOptions().Configure<DbSettings>(e => config.GetSection("DB").Bind(e))
.Configure<SmtpSettings>(e => config.GetSection("Smtp").Bind(e));
services.AddTransient<Demo>();
using (var sp = services.BuildServiceProvider())
{
while (true)
{
using (var scope = sp.CreateScope())
{
var spScope = scope.ServiceProvider;
var demo = spScope.GetRequiredService<Demo>();
demo.Test();
}
Console.WriteLine("可以修改配置了");
Console.ReadKey();
}
}
運行exe
![[assets/ASP.NET Core使用選項方式讀取配置/file-20250308123308971.png]]
修改配置文件保存
![[assets/ASP.NET Core使用選項方式讀取配置/file-20250308123433037.png]]
浙公網安備 33010602011771號