我的 AppConfig.json:
{
"MyTimeZone: "CET",
"RegularString" : "SomeValue",
"AnArray" : ["1","2"]
}
我的 POCO 課程:
public class Settings
{
public TimeZoneInfo MyTimeZone { get; set; }
public string RegularString { get; set; }
public IList<string> AnArray { get; set; }
}
注冊表.cs:
var configuration = GetConfiguration("AppSettings.json");
services.Configure<Settings>(configuration.GetSection("Settings"));
這當然不會將“CET”系結到有效的 TimeZoneInfo 物件中。現在的問題是我的應用程式(網路應用程式)中從字串轉換為 TimeZoneInfo 的最佳位置是什么?有沒有一種方法可以根據某些規則自動將字串配置值轉換為物件,而無需創建自定義轉換器?
uj5u.com熱心網友回復:
參考使用 DI 服務配置選項
services.AddOptions<Settings>()
.Configure<IConfiguration>((setting, configuration) => {
var section = config.GetSection("Settings");
//This will populate the other properties that can bind by default
section.Bind(setting);
//this will extract the remaining value and set it mnually
string value = section.GetValue<string>("MyTimeZone");
TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(value);
setting.MyTimeZone = info;
});
復雜的設定值可以通過 DI 直接從配置中提取,并用于創建時區并將其應用于設定。
uj5u.com熱心網友回復:
這只是我個人的看法,但我更喜歡 MyTimeZone 是一個 json 物件,而不是一個字串。考慮以下:
"Settings": {
"MyTimeZone": {
"ConfigureTimeZoneById": "CET"
},
"RegularString": "SomeValue",
"AnArray": [ "1", "2" ]
}
MyTimeZone.ConfigureTimeZoneById 不是實際資料物件的一部分。它只是將物件系結到配置的代理。TimeZone 類可能如下所示:
public class TimeZone
{
private string configureTimeZoneById { get; set; }
public string ConfigureTimeZoneById
{
get { return configureTimeZoneById; }
set
{
configureTimeZoneById = value;
InitializeTimeZone(value);
}
}
public string TimeZoneId { get; set; }
public string OtherProperties { get; set; }
private void InitializeTimeZone(string id)
{
var getTimeZone = TimeZonesDataset().FirstOrDefault(tzon => tzon.TimeZoneId.Equals(id));
if (getTimeZone != null)
{
this.TimeZoneId = getTimeZone.TimeZoneId;
this.OtherProperties = getTimeZone.OtherProperties;
}
}
//dummy dataset
private List<TimeZone> TimeZonesDataset() => new List<TimeZone> {
new TimeZone{TimeZoneId = "CET", OtherProperties = "Dummy properties to prove point"},
new TimeZone{TimeZoneId = "GMT", OtherProperties = default},
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447550.html
下一篇:在ASP.NET中回傳訊息框
