There is a simple approach to read values from appsettings.json file in AspNet Core. We write our custom configuration on appsetting.json file available on the root folder of the project.
Why do we need custom configuration?
In an application, there are some constants that need to be used throughout the application. Hard-coding them whenever and wherever we need it is always a bad practice on application development.
So, maintaining all these constants from the single place helps to create a maintainable software solution.
Sending an email is the basic feature which takes some parameters like hostname, port-no, password, company-email etc which doesn’t change frequently.
First Way
In ConfigureServices() method, we register the configuration with singleton instead of Configure() method.
Create a mailConfig class that hold the appsettings.json information.
The constructor injection on the controller of MailController
In ConfigureServices() method, we register the configuration with singleton instead of Configure() method.
Second Way
Register the configuration on ConfigureServices() method of Startup.cs class. The appsettings.json may consist many sections based on the requirement of the project. Notice that “mailConfig” on GetSection() method represents the section name.
Now we inject the IOptions<T> on the constructor of the Homecontroller.cs
You can see all the mail configs are read from appsettings.json |
Post a Comment