For this discussion let us assume we wish to store configuration in the file config.json
.
{
"epicswords":
{
"stormbringer": "elric",
"excalibur": "arthur"
}
}
If you start investigating configuration for .NET Core you'll discover reading from .json
files is extremely easy. Simply chain-in a call to the AddJsonFile
method when you're initializing your ConfigurationBuilder
at app start-up.
Configuration = new ConfigurationBuilder()
.AddJsonFile("config.json", true, true)
.Build();
Access to the data read from config.json
is again a simple matter.
IConfigurationSection epicSwords = Configuration.GetSection("epicswords")
To access individual epic swords you'd often see code like this:
string hero = Configuration.GetSection("epicswords")["excalibur"];
This works quite well and hero
will have the value "arthur" but personally I find that code's use of an indexer applied to a method result to be a bit awkward. I found an alternate method of accessing the data and I much prefer the look of the code.
string hero = Configuration["epicswords:excalibur"];
As before hero
will have the value "arthur" but the syntax has been simplified. I've also found the indexer on the Configuration
object to be quite resilient. If the path provided can be resolved to a single value it returns that value otherwise it returns null
. For example each of the following would return null
.
Configuration["epicswords"];
Configuration["epicswords:darthvader"];
Configuration["lukeskywalker"];
Configuration[""];
Note that "epicswords" is a valid path but because it does not resolve to a single value using it as an indexer key returns null.
In addition to its simplicity this notation works not just with parent-child nodes but as deep as needed, i.e. "{node0}:{node1}:{...nodeN}".
Pretty slick.