Search code examples
c#visual-studio-2019backgroundworker.net-core-3.1appsettings

How to use appsettings.json in Worker Service in .Net 3.1


When I try to run my windows service, the service is not starting up and I am getting the following error.

.NET Core Version: 3.1.11 Description: The process was terminated due to an unhandled exception. Exception Info: System.IO.FileLoadException: Could not load file or assembly 'Microsoft.Extensions.Configuration.Abstractions, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)

appsettings.json

{
   "myservice": {
    "production": "No",
    "staging": "No",
    "development": "Yes",
   }
}

public class Options
{
   public string Production { get; set; }
   public string Staging { get; set; }
   public string Development { get; set; }
}

Program.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) =>
            {
                services.Configure<Options>(hostContext.Configuration.GetSection("myservice"));
                services.AddHostedService<Worker>();
                services.AddTransient<Options>(_ => _.GetRequiredService<IOptions<Options>>().Value);
            })
    .UseWindowsService();
   }

Worker.cs

    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private BackgroundJobServer _server;
        private readonly Options _options; 
   
        public Worker(ILogger<Worker> logger, IOptions<Options> options)
        {
          _logger = logger;
          _options = options.Value;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
          _server = new BackgroundJobServer();
          while (!stoppingToken.IsCancellationRequested)
          {
              await Task.Delay(1000, stoppingToken);
          }
        }
    }

I tried different options and but I couldn't resolve the issue. Thanks for your help.


Solution

  • Seems that you updated nuget package to the version that is not compatible with the version of your framework (.net core 5.0 instead 3.1)