Configuration in .NET Core

Posted by Joe Enos on May 17, 2021 · 5 mins read

Here’s some basic examples for reading from a configuration file:

1) Create an appsettings.json file in your project.

2) Add this to your csproj file, so that it gets to your output directory:

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

3) Install the appropriate NuGet packages:

dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.Binder

4) Add data to your appsettings file, either as simple key-value pairs, or nest them:

{
"ApplicationName": "Some Application",

"ConnectionStrings": {
"CS1": "some-connection-string",
"CS2": "some-other-connection-string"
},

"Queries": {
"Q1": {
"ConnectionStringKey": "CS1",
"QueryText": "some query",
"Timeout": 40
},
"Q2": {
"ConnectionStringKey": "CS2",
"QueryText": "some other query"
}
}
}
5) Profit:

public class QueryInfo {
public string ConnectionStringKey { get; set; }
public string QueryText { get; set; }
}

var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();

string appName = config["ApplicationName"];
var queries = config.GetSection("Queries").GetChildren()
.Select(x => new
{
x.Key,
QueryInfo = x.Get<QueryInfo>()
}).ToArray();

foreach (var query in queries)
{
// Special GetConnectionString reads from "ConnectionStrings"
string connString = config.GetConnectionString(query.QueryInfo.ConnectionStringKey);
}