Configuration
A program needs settings that are not in its code — a port, a name, a path, a database address. The configuration system of .NET reads them from several sources into one tree of keys, and later sources override earlier ones. This lesson reads a JSON file, adds values from memory and from the environment, and converts the values to numbers and yes/no.
What you will learn#
- the idea of layered configuration (the last source wins),
- keys as paths:
App:Port, ConfigurationBuilderand the sources: JSON file, memory, environment variables,GetValuewith a type and a default,- sections (
GetSection,GetChildren), - where secrets belong.
The tutorial Settings saved the settings of a program in a file. This is the system that ASP.NET Core and most .NET programs use, and it works the same way for a web service and for a console tool.
The configuration providers (JSON, environment variables) are part of the ASP.NET Core runtime, so the program has the line "RingDotNet.Web" in its using { }: that starts the runtime with it (Getting started).
The program#
# configuration - settings from a JSON file, from memory and from environment variables, layered so that the last one wins
load "dotnet.ring"
using {
"System"
"System.IO"
"Microsoft.Extensions.Configuration"
"RingDotNet.Web" # the configuration providers are part of the ASP.NET Core runtime: this line starts it
}
func main
# A program needs settings that are not in its code: a port, a name, a path, the address of a database. The configuration system of
# .NET reads them from SEVERAL sources and puts them into one tree of keys. Sources added later override sources added earlier:
# defaults in a file, changes for a computer in the environment, a value for one run on the command line.
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_configuration.json"])
cJson = '{ "App": { "Name": "Demo", "Port": 8080, "Debug": false, "Features": [ "search", "export" ] }, "Database": { "Host": "localhost", "Timeout": 30 } }'
new File().WriteAllText([ :path = cFile, :contents = cJson ])
oBuilder = new ConfigurationBuilder
oBuilder = oBuilder.AddJsonFile([ :path = cFile ])
# 1. Keys are paths: "App:Name" is the key Name inside the section App. A list in the JSON becomes numbered keys (Features:0, Features:1).
oConfig = oBuilder.Build()
? "1. App:Name = " + oConfig.Item("App:Name") + ", App:Port = " + oConfig.Item("App:Port")
? " App:Features:1 = " + oConfig.Item("App:Features:1")
? " a key that does not exist is null: " + oConfig.Item("App:Missing").isNull()
# 2. Every value is TEXT. GetValue converts it to the type you ask for, and takes a default for a missing key
nPort = oConfig.GetValue([ :typeArguments = ["System.Int32"], :key = "App:Port" ])
lDebug = oConfig.GetValue([ :typeArguments = ["System.Boolean"], :key = "App:Debug" ])
nMissing = oConfig.GetValue([ :typeArguments = ["System.Int32"], :key = "App:Retries", :defaultValue = 3 ])
? nl + "2. the port as a number: " + nPort + " (+1 = " + (nPort + 1) + "), debug as a yes or no: " + lDebug + ", Retries (not set, default 3): " + nMissing
# 3. A section: GetSection gives a part of the tree. Its Key is the last name; GetChildren lists what is directly inside
oSection = oConfig.GetSection("Database")
? nl + "3. the section " + oSection.Key + " has:"
aChildren = oSection.GetChildren().toList()
for oChild in aChildren
? " " + oChild.Key + " = " + oChild.Value
next
# 4. More sources. AddInMemoryCollection adds values from a dictionary (good for defaults and for tests). Because it comes AFTER the
# file, its values win.
oOverrides = new Dictionary([ :typeArguments = ["System.String","System.String"] ])
oOverrides.Add("App:Port","9090")
oOverrides.Add("App:Extra","only in memory")
oBuilder.AddInMemoryCollection([ :initialData = oOverrides ])
oConfig2 = oBuilder.Build()
? nl + "4. after the memory source: App:Port = " + oConfig2.Item("App:Port") + " (was 8080), App:Name = " + oConfig2.Item("App:Name") + " (not changed), App:Extra = " + oConfig2.Item("App:Extra")
# 5. Environment variables. With a prefix, only the variables that start with it are read, and "__" in the name means ":" in the key.
# This is how a server or a container changes a setting without a new file.
new Environment().SetEnvironmentVariable([ :variable = "RDN111_Database__Host", :value = "db.example.com" ])
oBuilder.AddEnvironmentVariables([ :prefix = "RDN111_" ])
oConfig3 = oBuilder.Build()
? nl + "5. the environment variable RDN111_Database__Host changes Database:Host to: " + oConfig3.Item("Database:Host")
? " Database:Timeout is still from the file: " + oConfig3.Item("Database:Timeout")
new Environment().SetEnvironmentVariable([ :variable = "RDN111_Database__Host", :value = NULL ])
# 6. Where the value came from does not matter to the code that reads it. The order of the sources is the only rule: the last wins.
# Secrets (passwords, keys) do not belong in a file that is kept with the code: use environment variables or a secrets store.
new File().Delete(cFile)1. App:Name = Demo, App:Port = 8080
App:Features:1 = export
a key that does not exist is null: 1
2. the port as a number: 8080 (+1 = 8081), debug as a yes or no: 0, Retries (not set, default 3): 3
3. the section Database has:
Host = localhost
Timeout = 30
4. after the memory source: App:Port = 9090 (was 8080), App:Name = Demo (not changed), App:Extra = only in memory
5. the environment variable RDN111_Database__Host changes Database:Host to: db.example.com
Database:Timeout is still from the file: 30This program uses a few generic functions (dnStatic, dnNewGeneric, dnType) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Layers#
A ConfigurationBuilder collects sources; Build() reads them and gives the configuration. The sources are added in order and later sources override earlier ones. So the usual setup is: the defaults in a JSON file that comes with the program, then the settings of one computer or one environment (testing or production), then environment variables, then the command line. The code that reads a value does not know or care which source gave it. Every source is added by an extension method that the builder has as a method (the tutorial Caching). Each has several forms, so the names of the parameters choose one: oBuilder.AddJsonFile([ :path = cFile ]), oBuilder.AddInMemoryCollection([ :initialData = oDictionary ]), oBuilder.AddEnvironmentVariables([ :prefix = "APP_" ]).
Keys#
All the sources are turned into one flat set of keys with : between the levels: the JSON { "App": { "Port": 8080 } } gives the key App:Port, and a list becomes numbered keys (App:Features:0, App:Features:1). A key that does not exist gives null (isNull() on the result), not an error. Keys are not case sensitive. The indexer is read with Item(key).
Types#
Every value is a text. ConfigurationBinder.GetValue(configuration, type, key) converts it: Int32 for the port (8080, which you can add 1 to), Boolean for the debug flag (false or true). With a fourth value the call gives a default when the key is missing (Retries is 3). A text that cannot be converted raises an error, so a typo in a settings file is found when the program reads it.
Sections#
GetSection("Database") is a part of the tree; its Key is the name (Database) and GetChildren() lists the values and sub-sections directly inside it, each with Key and Value. A section can be given to a part of the program that does not need to know the rest of the settings.
Memory and environment#
AddInMemoryCollection takes a Dictionary<string,string> and is the best source for tests and defaults: the program needs no file. After it, App:Port is 9090 (it was 8080 in the file), App:Name is unchanged, and the new key App:Extra exists. Environment variables are how servers and containers change settings without a new file. With a prefix (RDN111_) only the variables that start with it are read, the prefix is removed, and __ (two underscores) means :, because : is not allowed in the name of an environment variable on every system. So RDN111_Database__Host changes Database:Host, while Database:Timeout still comes from the file.
A settings file that is kept with the code (in git, in a backup, on a shared disk) is not the place for passwords, keys and tokens. Read them from environment variables, from a secrets store or from a file outside the project, and never print the whole configuration in a log.
What you learned#
- configuration comes from layers, the last one wins,
- keys are paths with
:, values are text, AddJsonFile,AddInMemoryCollectionandAddEnvironmentVariables,GetValuewith a type and a default,- sections and children,
- secrets do not belong in the code.
Exercises#
- Add a second JSON file with the name
settings.local.jsonthat overrides some keys, and add it after the first. - Print the whole tree (every key and value) with a recursive function that uses
GetChildren. - Write
setting(cKey, xDefault)that reads a value and keeps the default when the key is missing. - Read the command line (
AddCommandLinewithsysargv, the tutorial A command-line tool) as the last source.