Reputation: 5503
How can I change where the appsettings.json
is searched for in a .Net Core 3.1 Worker Service
project
I've seen a few Asp.Net Core 2.*
examples, but nothing for 3.1
.
Below is my Program.cs
file. I know I need to change something here but I'm unsure what.
public class Program
{
public static void Main( string[ ] args )
{
CreateHostBuilder( args ).Build( ).Run( );
}
public static IHostBuilder CreateHostBuilder( string[ ] args ) =>
Host.CreateDefaultBuilder( args )
.UseWindowsService( )
.ConfigureServices( ( hostContext, services ) =>
{
services.AddHostedService<Worker>( );
} );
}
Why I want this
I need to containerize this application in to a WindowsServerCore
container. The appsettings.json
needs to be available and easily editable for technicians in the field.
I'm planning on bind mounting
a directory with the appsettings.json
from the host into the container. I'm unable to bind mount
the directory into my applications execution
directory as it will hide my executable
. This means I need to bind mount
into some other directory in the container (ex, C:\Configuration).
Because of this I want to change where the framework
searches for my appsettings.json
.
Upvotes: 2
Views: 1902
Reputation: 4078
Warning: I have not run the code snippet.
You can create a new instance of the ConfigurationBuilder
directly instead of using CreateDefaultBuilder
. The code would look something similar to below:
Host.CreateDefaultBuilder( args )
.ConfigureAppConfiguration(
(context, configurationBuilder) =>
{
configurationBuilder.SetBasePath("YOUR PATH")
.AddJsonFile("appsettings.json", false)
})
})
.UseWindowsService( )
.ConfigureServices( ( hostContext, services ) =>
{
services.AddHostedService<Worker>( );
} );
Or else, instead of using Default
settings you could also create your own ConfigurationBuilder
from scratch as below:
public static IConfiguration CreateConfiguration()
{
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath("YOUR PATH")
.AddJsonFile("appsettings.json", false)
.AddEnvironmentVariables();
return configurationBuilder.Build();
}
Upvotes: 2