gpt4 book ai didi

c# - IOptions 绑定(bind)不适用于嵌套类

转载 作者:行者123 更新时间:2023-12-05 07:13:34 24 4
gpt4 key购买 nike

我有一个 worker service ind dotnet core 3.1:

程序.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; }
}

版本 1:当我注入(inject) IOptions<A>在 Worker 类中,我从 ctor 获取默认值,尽管它是这样记录的:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1

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

我做错了什么?

最佳答案

如果我删除 BSettings = new List<B>();,版本 2 可以工作来自 ctor。

关于c# - IOptions 绑定(bind)不适用于嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60112229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com