Add Configuration to a .Net Core Console Application

December 05, 2020

This is another of those blog posts that’s probably been done before, but I keep having to collate a few pieces of information.

What we’re going to do here is create a .Net Core Console application, that reads an appsettings.json file, and a local secrets file. I covered some of this in an earlier post around creating a test harness in a .Net Core application.

If you’re using the console, then start with a new console app:



dotnet new console

We’ll need a few NuGet packages, too:



Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Configuration.UserSecrets

Wherever you’re reading the config, add the following snippet:



IConfiguration configuration = new ConfigurationBuilder()
               .AddJsonFile("appsettings.json", true, true)       
               .AddUserSecrets<Program>()
               .Build();

Since you’re bog standard console app doesn’t have an appsettings.json, you’ll need to add that; make sure you set the build action to “Copy if newer”:

config-console

And that’s it. To access the config, you can simply call:



Configuration.GetSection

If you wish to use GetValue then you’ll need the following package:



Install-Package microsoft.Extensions.Configuration.Binder

For example:



string connectionString = configuration.GetValue<string>("ServiceBusConnectionString");

References

https://www.twilio.com/blog/2018/05/user-secrets-in-a-net-core-console-app.html



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024