gpt4 book ai didi

c# - .net core 3.1 WorkerService 不加载配置选项/设置

转载 作者:行者123 更新时间:2023-12-02 16:47:13 26 4
gpt4 key购买 nike

使用 WorkerService (.net core 3.1) 的库存项目模板我无法获得 IOptions<x>去工作。

这是一个最小的复制:

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

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseConsoleLifetime()
.ConfigureServices((hostContext, services) =>
{
services.AddOptions();
services.AddHostedService<Worker>();
});
}

邮件设置

public class mailsettings
{
public string smtpserver { get; set; }
}

worker

public class Worker : BackgroundService
{
private readonly mailsettings _mailsettings;

public Worker(IOptions<mailsettings> mailsettings)
{
_mailsettings = mailsettings.Value;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine($"MailSettings SmtpServer: \"{(_mailsettings.smtpserver ?? "**null**")}\"");
Console.WriteLine(Directory.GetCurrentDirectory());
await Task.Delay(1000, stoppingToken);
}
}
}

appsettings.jsonappsettings.development.json 内容如下:

{
"mailsettings": {
"smtpserver": "mail.com"
}
}

这将写:

MailSettings SmtpServer: "null"

到控制台。应该写成

"mail.com".

我已经尝试了很多猜测...但无法得到任何结果。

最佳答案

邮件设置未配置到服务集合中,因此 DI 容器无法解析 IOPtions<mailsettings>

调用Configure<TOPtions>关于服务集合

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseConsoleLifetime()
.ConfigureServices((hostContext, services) => {
services
.AddOptions()
.Configure<mailsettings>(hostContext.Configuration.GetSection("mailsettings"))
.AddHostedService<Worker>();
});

引用 Configuration in ASP.NET Core

引用 Options pattern in ASP.NET Core

关于c# - .net core 3.1 WorkerService 不加载配置选项/设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60080527/

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