09 – .NET Core Console Application – Environment Variables
Environment variables can help by allowing the application to determine what environment its in and what adjustments it needs to make based on configuration settings for that environment.
Let go modify the Sameworks Application by expanding the project and opening the Program.cs file. In the section where load the appsetting.json configuration file I’ll add a line where I can set a variable with the name of the environment.
I’ll do that by calling Environment.GetEnvironmentVariable method and passing in the name of the environment variable name.
Next I’ll copy the line of code where I load the values from the appsettings.json configuration file and paste to add another line. Using string interpellation I’ll load a configuration file that contains the name of environment I want to apply.
I’ll need to create a matching file name so I’ll make a copy of the appsettings.json file and insert the name of the environment. I’ll modify the settings to reflect the newly created environment.
One final setting we need to make is on the Properties of the Project file where I can add the Environment Variable along with the value.
I’ll save everything and launch it…. You’ll see that the settings it loaded are now from the Development Environment.
We can add an appsettings.json file for a Production Environment as well. We can also create a profile that will set the appropriate environment variable value in order for the application to set the correct configuration values based on the file name that matches the environment variable.
We’ll select the correct profile for the Production Environment and launch it again.
In this case we still show the Development Environment Configuration Settings because I simply copied the file and forgot the modify its content. Let me make those adjustments real quick… Now you can see the changes that are loaded from the Production Configuration file.
In the next video I’ll wrap things up and provide you with some additional resources that will help you in the case you find yourself having to write a .NET Core Console Application.
See you there!