How to setup app settings in a .Net Core 3 Worker Service

If for example the worker class needed access to some data stored in your appsettings

public class Worker : BackgroundService {
    private readonly ILogger<Worker> logger;
    private readonly WorkerOptions options;

    public Worker(ILogger<Worker> logger, WorkerOptions options) {
        this.logger = logger;
        this.options = options;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
        while (!stoppingToken.IsCancellationRequested) {
            //do something that uses options

            logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(5000, stoppingToken);
        }
    }
}

Where WorkerOptions stores your values from configuration.

public class WorkerOptions {
    public string AminServiceUri { get; set; }
    public string BillServiceUri { get; set; }

    //... other properties
}

Which assumes the appsettings.json file has the corresponding keys

{
  "WCF": {
    "AminServiceUri":"http://localhost:45108/ServiceHost/v1/AminService.svc",
    "BillServiceUri":"http://localhost:45108/ServiceHost/v1/BillService.svc",

    //...other key-value pairs
  },
  "Logging": {
    "ExcessiveLogging": false
  }

}

By default Host.CreateDefaultBuilder will set up the usual configuration (appsettings.json et al).

Use hostContext.Configuration to get the IConfiguration instance that can be used to access the desired settings and add the strongly typed object model for it. Add that object to the service collection so that it can be injected where needed

For example

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) => {
                IConfiguration configuration = hostContext.Configuration;

                WorkerOptions options = configuration.GetSection("WCF").Get<WorkerOptions>();

                services.AddSingleton(options);

                services.AddHostedService<Worker>();
            });
}

When the worker is being created it will be injected with its required dependencies.

Reference Configuration in ASP.NET Core


How I did it:

Progam.cs:

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                IConfiguration configuration = hostContext.Configuration;
                services.Configure<RabbitMQConfiguration>(configuration.GetSection(nameof(RabbitMQConfiguration)));
                services.AddHostedService<Worker>();
            });
}

In your worker you can access the options like this:

public Worker(ILogger<Worker> logger, IOptions<RabbitMQConfiguration> options)
{
    _queue = options.Value.RabbitMQUrl;
    _options = options.Value;
    _logger = logger;
}

You'll also need a class for your options object:

public class RabbitMQConfiguration
{
    public string RabbitMQUrl { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
   // ...
}

In the appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "RabbitMQConfiguration": {
    "RabbitMQUrl": "rabbitmq://yoururl",
    "Username": "admin",
    "Password": "mypassword",
  }
}