Blog

Filter posts by Category Or Tag of the Blog section!

Worker Service tries to look for appsettings.json in System32 folder instead of local folder

Monday, 29 November 2021

In my previous post about running worker service in windows as a windows service, I coveted the required operations from converting to hosting. But in the case that reading some details from JSON file like appsetting, you may get the following error:



Although the error could have different reasons but, if you use
GetCurrentDirectory you will get the error about the file directory as windows would try to find the appsetting from the win32 folder. First of all, you can add your JSON file right after calling the UseWindowsService():

 

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json");
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });
}


Besides, if you are using a JSON file in another assembly, you don’t have to get the content by using GetCurrenctDirectory(). An example, in the OnConfiguring() method of Entity Framework that usually lives in a separate assembly, you shouldn't use GetCurrentDirectory at all if you are going to run your worker service as a windows service. Simply use AddJsonFile():

 

 protected override void OnConfiguring(DbContextOptionsBuilder builder)
        {
            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.AddJsonFile("appsettings.json");
            var root = configurationBuilder.Build();
            var connectionString = root.GetConnectionString("MyConnection");
            builder.UseSqlServer(connectionString, x => x.MigrationsHistoryTable("Migration", "MyDB"));
            base.OnConfiguring(builder);
        }


 

Category: Software

Tags: Dot Net

comments powered by Disqus