I have a .Net core worker service, which I am running as a windows service. The service is using appsettings.json file for the config information. After installing the service using SC CREATE
command, the service was failing.
In the event viewer I found the error it cannot find the file C:\Windows\System32\appsettings.json
. My service files are placed in a different folder c:\Services\
, instead of looking at that location, the service is looking for a the file in System32 folder.
The configuration registration is as below.
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = configBuilder.Build();
services.AddSingleton(configuration);
How can I make the service to look at the local folder?
appsettings. json is one of the several ways, in which we can provide the configuration values to ASP.NET core application. You will find this file in the root folder of our project.
Yes, I'm leaving appsettings. json in the project and it's being deployed - for documentation and non-sensitive settings. And, yes, I could leave sensitive data encrypted in Visual Studio Online but for now, the simplest thing to do is hide an overriding version elsewhere in the file system, as I'm doing.
The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.
In order to add AppSettings. json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button. Once the File is created, it will have a DefaultConnection, below that a new AppSettings entry is added.
That's because the current directory is changed to C:\Windows\System32
at runtime. You could get a relative path by Assembly.GetExecutingAssembly()
. For example:
var configBuilder = new ConfigurationBuilder()
.SetBasePath( Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location))
.AddJsonFile("appsettings.json");
var configuration = configBuilder.Build();
I´ve successfully used the docs in Host ASP.NET Core in a Windows Service
In a nutshell, you should just add .UseWindowsService()
in your configuration builder step, like in the following:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostContext, configuration) =>
{
//...set your configurations here
})
.ConfigureServices((hostContext, services) =>
{
//...configure you services here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With