Reading appsettings.json file in .NET 6 console app
Asked Answered
L

2

3

How to get settings from an appsettings.json file in a .NET 6 console application?

program.cs file:

public class Program
{
    private static ManualResetEvent _quitEvent = new ManualResetEvent(false);
    
    private static void Main(string[] args)
    {
        // Setup Host
        var host = CreateDefaultBuilder().Build();
    
        host.Run();
    }
    
    private static IHostBuilder CreateDefaultBuilder()
    {
        return Host.CreateDefaultBuilder()
                   .ConfigureAppConfiguration(app =>
                    {
                        app.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                    })
                   .ConfigureServices(services =>
                    {
                        // this is the line that has the issue
                        services.Configure<MailSettings>(services.Configuration.GetSection("MailSettings"));
                    });
    }
}

The line above throws an error:

Error CS1061
'IServiceCollection' does not contain a definition for 'Configuration' and no accessible extension method 'Configuration' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

How to configure it properly?

Lanti answered 9/10, 2022 at 7:30 Comment(0)
P
2

First, install Microsoft.Extensions.Configuration package from NuGet.

Microsoft.Extensions.Configuration package

Now write a method like:

private static IConfiguration GetConfig()
{
    var builder = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
    return builder.Build();
}

Suppose your appsettings.json file look like:

appsettings.json file

Now get appsettings.json value from Main method:

public static void Main(string[] args)
{
    var config = GetConfig();
    // Read DB connection
    string connectionString = config.GetConnectionString("Default")
    // Read other key value
    string baseUri = config.GetSection("SomeApi:BaseUrl").Value;
    string token = config.GetSection("SomeApi:Token").Value;
}

Hope you get enjoy coding.

Phene answered 12/12, 2022 at 4:55 Comment(0)
C
0

You probably intended to use the delegate passing in the HostBuilderContext parameter which has the Configuration property:

.ConfigureServices((context, services) => // accept context parameter
{
    services.AddSingleton<IMailService>();
    services.Configure<MailSettings>(context.Configuration.GetSection("MailSettings"));
});
Calefactory answered 9/10, 2022 at 8:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.