read configuration workerservice 1

read configuration workerservice

public class Program {
    public static void Main(string[] args) {

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

                WorkerOptions options = configuration



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

    public Worker(ILogger 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);

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

    //... other properties

//File appsettings.json
  "WCF": {

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


Here is what the above code is Doing:
1. The Main method is the entry point for the application. It builds and runs the host.
2. The CreateHostBuilder method configures the host. It adds the Worker class to the service container.
3. The Worker class is the background service. It uses the WorkerOptions class to get the configuration values.
4. The WorkerOptions class is a POCO class that holds the configuration values.
5. The appsettings.json file contains the configuration values.

Similar Posts