.net core 3.1 WorkerService 未加载配置 options/settings

.net core 3.1 WorkerService not loading configuration options/settings

使用 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; }
}

工人

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