-
It seems like net8 is now recommending use of 'Host.CreateApplicationBuilder' rather than 'Host.CreateDefaultBuilder'. I was able to bind
How can I do similar with new
Full sample: WorkerServiceTest.csproj:
appsettings.json:
Program:
Worker:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It's because of this: builder.Services.AddOptions<DatabaseConfig>().BindConfiguration("DatabaseConfig"); // <- Empty
builder.Services.AddSingleton<DatabaseConfig>(); That first line is setting up using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace WorkerServiceTest;
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger, IOptions<DatabaseConfig> options)
{
var databaseConfig = options.Value;
Debug.Assert(databaseConfig.ConnectionString1.Equals("this"));
Debug.Assert(databaseConfig.ConnectionString2.Equals("that"));
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
await Task.Delay(1000, stoppingToken);
}
}
} |
Beta Was this translation helpful? Give feedback.
It's because of this:
That first line is setting up
IOptions<DatabaseConfig>
which is where configuration is being bound, and you're also addingDatabaseConfig
directly. UseIOptions<DatabaseConfig>
instead.