4

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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"));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.