IOptions绑定不适用于嵌套类

我有一个工人服务ind dotnet core 3.1:

Program.cs:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    var builder = new ConfigurationBuilder()
                        .AddJsonFile("appsettings.json", optional: false)
                        .AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true)
                        .AddEnvironmentVariables();

                    var configuration = builder.Build();

                    services.AddOptions();

                    // Version 1
                    services.Configure<A>(configuration);

                    // Version 2
                    //services.Configure<A>(o => configuration.GetSection("PollingSettings").Bind(o));

                    services.AddHostedService<Worker>();
                })
                .UseWindowsService();
    }

appsettings.Development.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "A": {
    "option1": "value1_from_json",
    "option2": -1,
    "BSettings": [
      {
        "Option1": "xxx",
        "Option2": 1
      }
    ]
  }
}

A.cs:

public class A
{
    public A()
    {
        Option1 = "value1_from_ctor";
        BSettings = new List<B>();
    }

    public string Option1 { get; set; }
    public int Option2 { get; set; } = 5;

    public List<B> BSettings { get; set; }
}

B.cs:

public class B
{
    public string Option1 { get; set; }
    public int Option2 { get; set; }
}

Version 1: As I inject IOptions<A> in the Worker class, I get the default values from the ctor, although it is documented so: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1

版本2: 根Option1和Option2从appsettings中填充,但是BSettings列表默认为空。

我怎么了

评论
  • 小、白痴
    小、白痴 回复

    The Version 2 works if I remove the BSettings = new List<B>(); from the ctor.