I am using a dotnet core 7 worker project in which I want to add app settings to my program.cs class but for that I need an Iconfiguration from the host context. How can I get and inject it as a singleton in the project?
Here is my code:
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
// Here I want to add a configuration from appsettings.json and then map it to my Configuration class
services.AddHostedService<Worker>();
})
.Build();
host.Run();
Here are my appsettings:
{
"ServiceName":"Test service",
"connectionString":""
}
public class Configuration{
public string ServiceName {get;set;}
public string ConnectionString {get;set;}
}
>Solution :
You can use the Bind method to bind the Configuration segment to a static typed object instance.
Configuration.GetSection(PositionOptions.Position).Bind(positionOptions);
Or even more convenient the Get method
Configuration.GetSection(PositionOptions.Position).Get<PositionOptions>()