我是 .net core 的新手,我在為單個 POCO 使用多個配置提供程式時遇到問題。我使用的是 .net 核心,而不是 asp.net 核心。
為了清楚起見,我試圖簡化類,請忽略任何編譯錯誤。我的配置模型如下:
public class Configurations
{
public EnvironmentConfig EnvironmentConfig {get; set;}
public ServerConfig ServerConfig {get; set;}
}
public class EnvironmentConfig
{
public string EnvironmentStr {get; set;}
}
public class ServerConfig
{
public string Address {get; set;}
public string Username {get; set;}
public string Password {get; set;}
}
我有兩個提供者 -appsettings.json和一個資料庫。該資料庫與其他服務一起使用,因此無法輕松更改資料(可以將其視為只讀)。該appsettings.json檔案具有以下層次結構:
{
"EnvironmentConfig": {
"EnvironmentStr": "dev"
},
"ServerConfig": {
"Address": "https://example.com"
// the other properties are not here, they're kept only in the database
}
}
資料庫沒有層次結構,僅提供缺少的屬性(為了保持一致性,我將再次使用 JSON):
{
"Username": "user"
"Password": "password"
}
當我嘗試獲取一個IOptionsMonitor<Configurations>物件時,只有Address屬性填充在里面ServerConfig,就像它只是從讀取appsettings.json(用戶名和密碼在根級別,所以它沒有正確系結它們):
var configs = host.Services.GetService<IOptionsMonitor<Configurations>>().CurrentValue;
{
"EnvironmentConfig": {
"EnvironmentStr": "dev"
},
"ServerConfig": {
"Address": "https://example.com"
"Username": null,
"Password": null
}
}
當我嘗試獲取一個IOptionsMonitor<ServerConfig>物件時,它只系結資料庫中的資料:
var serverConfig = host.Services.GetService<IOptionsMonitor<ServerConfig>>().CurrentValue;
{
"Address": null,
"Username": "user",
"Password": "password"
}
看起來我沒有正確系結它。我嘗試了多種方法,但沒有奏效:
public static IServiceCollection AddConfiguration(this IServiceCollection services, IConfiguration configuration)
{
services
.Configure<ServerConfig>(configuration) // the db properties are also at root level
.Configure<Configurations>(configuration);
return serviceCollection;
}
public static IServiceCollection AddConfiguration(this IServiceCollection services, IConfiguration configuration)
{
services
.AddOptions<ServerConfig>()
.Bind(configuration.GetSection("ServerConfig");
services
.AddOptions<Configurations>()
.Bind(configuration);
return serviceCollection;
}
有人能解釋一下如何正確系結它,不管層次結構ServerConfig有什么不同,所以在里面填充了所有屬性Configurations嗎?
uj5u.com熱心網友回復:
我假設資料庫是作為自定義配置提供程式訪問的
更新來自資料庫的鍵以匹配所需的層次結構
資料庫:
"ServerConfig:Username" -> "user"
"ServerConfig:Password" -> "password"
因此,配置框架在合并來自多個配置提供程式的所有配置時知道您指的是什么。
從資料庫中提取設定,并在加載配置時將層次結構添加到鍵中。
簡化示例:
public class ServerConfigProvider : ConfigurationProvider {
public ServerConfigProvider (Action<DbContextOptionsBuilder> optionsAction) {
OptionsAction = optionsAction;
}
Action<DbContextOptionsBuilder> OptionsAction { get; }
public override void Load() {
var builder = new DbContextOptionsBuilder<MyEFConfigurationContext>();
OptionsAction(builder);
using (var dbContext = new MyEFConfigurationContext(builder.Options)) {
Data = dbContext.MySettingsTable.ToDictionary(c => $"ServerConfig:{c.Key}", c => c.Value);
}
}
}
參考自定義配置提供程式
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/372174.html
下一篇:如何將多個內容寫入文本檔案
