我有一个简单的HostedService
,我正在尝试从appsettings.customs.json
文件中读取一些强类型的配置。这是应用程序设置的内容:
{
"ApproveSetting": {
"CallCount": 1,
"Sleep": "00:00:05"
},
"TrySetting": {
"TryLifeTime": "03:00:00",
"DelayTime": "00:00:30"
}
}
然后我添加.json
文件并绑定如下配置:
public class Program {
static void Main(string[] args) => CreateHostBuilder(args).Build().Run();
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureAppConfiguration((hostContext, configuration) => {
configuration.AddJsonFile("appsettings.customs.json", false, true);
})
.ConfigureServices((hostContext, services) => {
services.AddOptions();
// tried both with and without the Bind(t) method
services.Configure<ApproveSetting>(
hostContext.Configuration.GetSection("ApproveSetting"));
// tried both with and without the Bind(t) method
services.Configure<TrySetting>(t
=> hostContext.Configuration.GetSection("TrySetting").Bind(t));
// blah blah blah
});
}
当我尝试解析服务中的Settings
时,我仅获得TrySetting
的值,并且ApproveSetting
由默认值初始化。看来它只读取TrySetting
,而不读取ApproveSetting
。
如您所见,我已经尝试了Configure(Secion)
和Configure(t => ...Bind)
方法。另外,我还尝试过更改.json
文件中各节的位置。
你知道这里发生了什么吗?
更新:
ApproveSetting
类:
public class ApproveSetting {
public int CallCount { get; set; }
public TimeSpan Sleep { get; set; }
}
TrySetting
类:
public class TrySetting {
public TimeSpan TryLifeTime { get; set; }
public TimeSpan DelayTime { get; set; }
}
更新2:答案:
最后我找到了问题。问题是我在两个不同的命名空间中有两个ApproveSetting
和TrySetting
类。我正在namespace1
中注册它们,并试图解决namespace2
中的主题。所以,我不好。