gpt4 book ai didi

asp.net-core - 将 .NET Core IConfiguration 注入(inject)单例

转载 作者:行者123 更新时间:2023-12-05 01:44:00 24 4
gpt4 key购买 nike

我想在整个应用程序中使用以下 Singleton 类:

public sealed class AppSettings
{
private static readonly Lazy<AppSettings> _lazy =
new Lazy<AppSettings>(() => new AppSettings());

private AppSettings()
{
// I want to inject this
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true);

Config = builder.Build();
}

public static AppSettings Instance => _lazy.Value;

public IConfigurationRoot Config { get; }
}

我想注入(inject) IConfiguration 而不是在其中构建它。我该怎么做?

最佳答案

您不需要创建自己的单例类。相反,创建一个普通类并将其作为单例注册/添加到 DI 容器:

public sealed class AppSettings
{
private IConfiguration _configuration;

public AppSettings(IConfiguration configuration)
{
_configuration = configuration;
}

...
}

然后在 ConfigureServices 方法中使用

// IConfigurationRoot ConfigureServices;

services.AddSingleton(new AppSettings(Configuration));

关于asp.net-core - 将 .NET Core IConfiguration 注入(inject)单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47820196/

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