gpt4 book ai didi

c# - 在没有 DI 的控制台应用程序中将 IConfigurationSection 与可刷新配置绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 14:48:25 25 4
gpt4 key购买 nike

我在 .Net Core 控制台应用程序中使类型化配置可刷新时遇到问题。

应用程序将从配置中加载类型化对象...

{
"LibrarySettings": {
"SettingA": "ValueA",
"SettingB": "ValueB"
}
}

... 并将它们作为 IOption<SomeLibrarySettings> 传递给图书馆

public class LibrarySettings
{
public string SettingA { get; set; }
public string SettingB { get; set; }
}

public class BusinessLogic
{
private IOptions<LibrarySettings> _settings;

public BusinessLogic(IOptions<LibrarySettings> settings)
{
_settings = settings;
}

public string GetValueA => _settings.Value.SettingA;

public string GetValueB => _settings.Value.SettingB;
}

在运行时,如果我改变 appsettings.json我会期待底层 IOptions相应地更新值的实例。

public class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true);

var configuration = builder.Build();

LibrarySettings settings = new LibrarySettings();

configuration.Bind("LibrarySettings", settings);

BusinessLogic logic = new BusinessLogic(Options.Create(settings));

while (true)
{
configuration.Reload();
Console.WriteLine();
Console.WriteLine(logic.GetValueA);
Console.WriteLine(logic.GetValueB);
Console.ReadLine();
}
}
}

不幸的是,情况并非如此。当我启动此代码并更改复制的值时 appsettings.json应用程序中的值不会重新加载。

我做错了什么?

最佳答案

使用IOptionsSnapshot代替IOptions

public class BusinessLogic
{
private IOptionsSnapshot<LibrarySettings> _settings;

public BusinessLogic(IOptionsSnapshot<LibrarySettings> settings)
{
_settings = settings;
}

public string GetValueA => _settings.Value.SettingA;

public string GetValueB => _settings.Value.SettingB;
}

引用 Options patterns in ASP.NET Core

编辑:为避免常见错误('T' 必须是具有公共(public)无参数构造函数的非抽象类型)

public class LibrarySettings
{
public string SettingA { get; set; }
public string SettingB { get; set; }
public LibrarySettings() {}
}

开始工作了:

class Program
{

static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true);

var configuration = builder.Build();

var settings = new LibrarySettings();

configuration.GetSection("LibrarySettings").Bind(settings);

var x = settings.SettingA;
}

}

public class BusinessLogic
{
private LibrarySettings _settings;

public BusinessLogic(IOptionsSnapshot<LibrarySettings> settings)
{
_settings = settings.Value;
}

public string GetValueA => _settings.SettingA;

public string GetValueB => _settings.SettingB;
}
public class LibrarySettings
{
public string SettingA { get; set; }
public string SettingB { get; set; }
public LibrarySettings() { }
}

关于c# - 在没有 DI 的控制台应用程序中将 IConfigurationSection 与可刷新配置绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53053322/

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