Configuration Model in ASP.NET CORE
Compared to other versions of ASP.Net, ASP.Net Core has a lot of changes. There is a new way to configure the settings. Let’s see the changes in the architecture.
No More web.config
In earlier versions we used to add all the settings that we need within the appsettings node including connection with database. To access these values we used Configuration Manager class.Spmething like this:
ConfigureManager.AppSettings[“SmtpServer”];
Introduction Of appsettings.json
Asp.Net Core has made it possible to read settings from different sources like XML, JSON and INI files. Let us see how it works in a sample web Application.
- Open Visual Studio 2015 Update 3 or higher version.
- File >> New Project >> Asp.Net Core Web Application
- Choose Web Application from the Template.
Now let us store the SMTP info in the appsettings.json file as shown in the figure below:
The main advantage in this configuration model is that it’s easy to create a new class to work with the data. We will see this in an example as shown in the figure below by creating a new class and let it call SmtpConfig class inside a new folder in the Solution Explorer. Likewise define the properties too.
Now let’s go the StartUp.cs and there already exits some code within the constructor to read the appsettings.json file:
Now we have to add is some code in the StartUp.cs to read the SMTP section.
Go to the ConfigureServices function and add following code:
Don’t forget to use the namespace or just point the cursor to the error,Visual Studio will automatically provide you the namespace.
Asp.Net Core has built-in dependency injection. We will use IOptions<T> Interface to inject the Smtp class. Let’s head on to the HomeController.
Use the namespace Microsoft.Extensions.Options.
Before running the application let create a debug point in the HomeController to see the constructor injecting the object type SmtpConfig through IOptions<SmtpConfig> and assigning it to a property of the same type:
Configuring Multiple Environments
Incase we need different configuration values for different environments then we have to first determine the einvironment(dev,QA, production)etc. To do that Lets add a new JSON file and set the name appsettettings2.json then add only the smtp section wtih the values associated with this new environment:
And add some values in it:
There is an environment variable called Hosting: Environment which gives us the knowledge what is the current environment.
To access it go to the properties of the project >> Debug Tab and change the value.