我的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; }
}Registry.cs:
var configuration = GetConfiguration("AppSettings.json");
services.Configure<Settings>(configuration.GetSection("Settings"));当然,这不会将"CET“绑定到有效的TimeZoneInfo对象。现在的问题是,在我的应用程序(一个web应用程序)中,将字符串转换为TimeZoneInfo的最佳位置是什么?是否有一种在不创建自定义转换器的情况下根据特定规则自动将字符串配置值转换为对象的方法?
发布于 2022-03-19 16:07:47
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直接从配置中提取复杂的设置值,并用于创建时区并将其应用于设置。
发布于 2022-03-20 04:12:21
这只是我个人的观点,但我更希望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://stackoverflow.com/questions/71539089
复制相似问题