TopshelfHosting icon indicating copy to clipboard operation
TopshelfHosting copied to clipboard

Problem with reading appsettings file using Host.CreateDefaultBuilder

Open valeriob opened this issue 6 years ago • 4 comments

Creating a default host builder via this api var builder = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) it does not load appsettings.json settings.

This is due to CreateDefaultBuilder setting the content root to
builder.UseContentRoot(Directory.GetCurrentDirectory()); https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.0 and at that time GetCurrentDirectory is c:\windows\system32

valeriob avatar Nov 04 '19 10:11 valeriob

@valeriob According to Host ASP.NET Core in a Windows Service on Microsoft Docs, GetCurrentDirectory() always returns C:\Windows\system32 for Windows Services.

It does state, however, that loading the app's default settings files - appsettings.json and appsettings.{Environment}.json - are loaded from the app's content root by calling Host.CreateDefaultBuilder(args).

Does it make any difference if you call RunAsTopshelfService after CreateDefaultBuilder?

Alternatively, you might workaround this issue by calling:

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

stevenvolckaert avatar Feb 28 '20 09:02 stevenvolckaert

Hi, you can replace Directory.GetCurrentDirectory() by using the path of the proccess:

CreateHostBuilder(args)
  // set base path for application
  .UseContentRoot(Path.GetDirectoryName(Process
    .GetCurrentProcess()
    .MainModule.FileName))
  .RunAsTopshelfService();

vunb avatar Jan 15 '21 08:01 vunb

The only solution worked is the same as used in UseWindowsService() extension:

var rc = CreateHostBuilder(args)
  .UseContentRoot(AppContext.BaseDirectory)
  .RunAsTopshelfService();

lekrus avatar Jan 28 '21 07:01 lekrus

The only solution worked is the same as used in UseWindowsService() extension:

var rc = CreateHostBuilder(args)
  .UseContentRoot(AppContext.BaseDirectory)
  .RunAsTopshelfService();

Thank you soooooooooo much

EsmailOuadghiri avatar Apr 13 '21 15:04 EsmailOuadghiri