Break point B2: All settings of the Order Book are in App.config and are read through System.Configuration. Microsoft's documentation
calls that an intermediate step that keeps working on .NET, and advises following the way of the libraries: they read appsettings.json through
Microsoft.Extensions.Configuration. This lesson takes that step, and it uses the opportunity to give the program an orderly startup.
You know the basics of configuration, options and dependency injection from K2, module 2.3 (ASP.NET Core). What matters here is what is different in
a Windows program: there is no WebApplication that takes over the startup.
From this lesson on, the net48 target is dropped. The multi-target program has served its purpose: it let you compare the tests on both runtimes.
Configuration and startup use things that exist only on .NET (ApplicationConfiguration, the host). The old state is in the
fallback package and in the Git tag before-net10.
From App.config to appsettings.json
| App.config | appsettings.json | |
|---|---|---|
| Format | XML, sections appSettings and connectionStrings |
JSON, nested as you like |
| Reading | ConfigurationManager.AppSettings["Name"], text only |
IConfiguration, binding to classes |
| Overriding | per machine through .config files |
environment variables, command line, user secrets, appsettings.<Environment>.json |
| Validating | when reading, by hand every time | at startup, with rules |
The values of App.config move one to one into the new file, with an OrderBook section for the settings:
{
"ConnectionStrings": {
"OrderBook": "Server=(localdb)\\MSSQLLocalDB;Database=OrderBook;Integrated Security=SSPI"
},
"OrderBook": {
"HourlyRate": 68.00,
"CallOutFee": 29.50,
"Vat": 0.19,
"ExportFolder": "\\\\brandt-srv01\\Accounting\\OrderBook",
"DispatchGroup": "BRANDT\\Dispatch"
}
}
The connection string is in the ConnectionStrings section, where GetConnectionString finds it. It contains no password; the program signs in with
the Windows login. If secrets were added, they would never belong in this file. Module 5 (lesson M5.3) shows where they go instead.
The file has to be shipped with the program. For that, the project file has the entry CopyToOutputDirectory with PreserveNewest. The default host
then loads the file by itself.
The order in which the host reads sources, from strongest to weakest, is named in Microsoft's documentation: command line, environment variables,
user secrets (only in the Development environment), appsettings.<Environment>.json, appsettings.json. A later source overrides the earlier one. That way you
can change a value on one machine without touching the file, for example the hourly rate with the environment variable OrderBook__HourlyRate. Two
underscores replace the colon.