TopshelfHosting
TopshelfHosting copied to clipboard
Problem with reading appsettings file using Host.CreateDefaultBuilder
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 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>();
});
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();
The only solution worked is the same as used in UseWindowsService() extension:
var rc = CreateHostBuilder(args)
.UseContentRoot(AppContext.BaseDirectory)
.RunAsTopshelfService();
The only solution worked is the same as used in UseWindowsService() extension:
var rc = CreateHostBuilder(args) .UseContentRoot(AppContext.BaseDirectory) .RunAsTopshelfService();
Thank you soooooooooo much