无法绑定appsettings.json中的某些自定义配置

时间:2020-07-28 20:17:00

标签: c# .net-core appsettings .net-core-3.1 asp.net-core-hosted-services

我有一个简单的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:答案:

最后我找到了问题。问题是我在两个不同的命名空间中有两个ApproveSettingTrySetting类。我正在namespace1中注册它们,并试图解决namespace2中的主题。所以,我不好。

0 个答案:

没有答案