Search code examples
c#.net-coreconsole-application

How to get Configuration from appsettings in .NET Core console application


I am using a .NET Core 7 worker project in which I want to add app settings to my program.cs class, but for that I need an IConfiguration interface 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 is my appsettings.json:

{
    "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>()