06 – .NET Core Console Application – AppSettings
Let’s add an app settings dot json file to the Sameworks Project.
• We’ll right-click on the project
• Add a new item
• Scroll to find JavaScript JSON Configuration File
○ Call it appsetting.json (all lower-case)
Because this file is not part of the build and doesn’t get compiled into the code we have to tell the build process to copy it into the same directory where the compiled executables will exist. We’ll do so by:
• Right-clicking on the appsettings.json file
• Select properties
• Change the [Copy to Output Directory] to [Copy Always] or [Copy if newer]
○ It’s your choice
○ I prefer [Copy Always]
We’ll clear out the contents of the file and replace the body with:
• ConnectionStrings – as you can tell it’s a JSON Format
• In ConnectionStrings we’ll add a “DefaultConnection”
○ We’ll include a value that resembles a valid connection string
Now we’ll modify Program.cs by adding a call to [ConfigureAppConfiguration] which takes a function with 2 parameters:
• Context
• Configuration
Using the “fat-arrow” function we’ll fill in the body. We’ll start by clearing any configuration settings that currently in place. Next we’ll add the [appsettings.json] file to the configuration. Set a couple of arguments:
• Optional = true: in case the file doesn’t exist
• Reload on Change = true: allows you modify the file while the app is running and reloads the settings automatically.
Let’s go into the Worker.cs file so we can get the [Connection String] from app settings. Make sure that “DefaultConnection” is spelled the same way you spelled it in the appsettings.json file.
We’ll log it out to the console using a little string interpolation.
Let’s run it and see if it works.
SHAZAAM!!! There it is! The connection string just as we have it in the appsettings.json file.
In the next video we’ll talk about Command Line Arguments… We’ll see you there.