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?
First, install Microsoft.Extensions.Configuration package from NuGet.

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:

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With