Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get Configuration from appsettings in dotnet core console application

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{

"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.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-7.0#bind-hierarchical-configuration-data-using-the-options-pattern

Configuration.GetSection(PositionOptions.Position).Bind(positionOptions);

Or even more convenient the Get method

 Configuration.GetSection(PositionOptions.Position).Get<PositionOptions>() 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading