AppSettings - Six Ways To Read The Config In ASP.NET CORE 3.0

In this article, you will learn six ways to read all settings on the AppSettings.JSON file in an ASP.NET CORE 3.0 web application.
 
With the ASP.NET CORE, the WEB.CONFIG file was totally out of use, but if you want to Host an ASP.NET CORE Web Application on IIS, you must still use it.
 
So, we are talking about the AppSettings.JSON file, and there are lots of ways to read it.
 
Imagine a settings file written this way,
  1. {  
  2.     "Logging": {  
  3.         "LogLevel": {  
  4.             "Default""Information",  
  5.             "Microsoft""Warning",  
  6.             "Microsoft.Hosting.Lifetime""Information"  
  7.         }  
  8.     },  
  9.     "MySettings": {  
  10.         "Log"true,  
  11.         "ConnectionStringId""Default",  
  12.         "Parameters": {  
  13.             "IsProduction"true  
  14.         }  
  15.     },  
  16.   "AllowedHosts""*"  
  17. }  
For this article, let’s try to read the IsProduction (bool) property in six different ways. Shall we?
 
#1 AppSettings – GetSection
 
The first simple way is to use the GetSection method from the IConfiguration interface reading parent/child tags like this: 
  1. [ApiController]  
  2. [Route("[controller]")]  
  3. public class Way1Controller : ControllerBase  
  4. {  
  5.     private readonly IConfiguration _configuration;  
  6.    
  7.     public Way1Controller(  
  8.         IConfiguration configuration)  
  9.     {  
  10.         _configuration = configuration;  
  11.     }  
  12.    
  13.     [HttpGet]  
  14.     public bool Get()  
  15.     {  
  16.         return bool.Parse(_configuration.GetSection("MySettings").GetSection("Parameters").GetSection("IsProduction").Value); // here  
  17.     }  
  18. }  
To reach the IsProduction property, it’s necessary first to read MySettings and Parameters tags.
 
The property Value will return a String with value “true” the same as configured on the AppSettings.JSON file.
 
Finally, we need to convert the String value to Boolean one. 
 
#2 AppSettings – GetSection e GetValue
 
The second way is a little bit better than the first one. Just use the GetValue method and be explicit about what type want to convert it to.   
  1. [ApiController]  
  2. [Route("[controller]")]  
  3. public class Way2Controller : ControllerBase  
  4. {  
  5.     private readonly IConfiguration _configuration;  
  6.    
  7.     public Way2Controller(  
  8.         IConfiguration configuration)  
  9.     {  
  10.         _configuration = configuration;  
  11.     }  
  12.    
  13.     [HttpGet]  
  14.     public bool Get()  
  15.     {  
  16.         return _configuration.GetSection("MySettings").GetSection("Parameters").GetValue<bool>("IsProduction"); // here  
  17.     }  
  18. }  
Like you can see, automatically converting String to Boolean is very good but still, it has lots of code repetition calling the GetSection method.
 
#3 AppSettings – GetValue inline
 
The third and more elegant way is to write all properties inline and in order, separated by a colon. 
  1. [ApiController]  
  2. [Route("[controller]")]  
  3. public class Way3Controller : ControllerBase  
  4. {  
  5.     private readonly IConfiguration _configuration;  
  6.    
  7.     public Way3Controller(  
  8.         IConfiguration configuration)  
  9.     {  
  10.         _configuration = configuration;  
  11.     }  
  12.    
  13.     [HttpGet]  
  14.     public bool Get()  
  15.     {  
  16.         return _configuration.GetValue<bool>("MySettings:Parameters:IsProduction"); // here  
  17.     }  
  18. }  
You have to agree with me, that way is much better than the other two.
 
But we are still writing lots of String words on the GetValue method and injection the IConfiguration interface in the controller’s constructor.
 
Imagine if we have lots of controllers, we need to repeat this code across all controllers, and this is not a good programming practice. 
 
#4 AppSettings – GetSection e Binding
 
The fourth way is to connect (like a binding) one class instance to a corresponding tag in the AppSettings.JSON file.
 
Let’s create a class called MySettingsConfiguration with the same properties above MySettings tag in the AppSettings.JSON file.  
  1. public sealed class MySettingsConfiguration  
  2. {  
  3.     public bool Log { getset; }  
  4.     public string ConnectionStringId { getset; }  
  5.     public Parameters Parameters { getset; }  
  6. }  
  7.    
  8. public sealed class Parameters  
  9. {  
  10.     public bool IsProduction { getset; }  
  11. }  
Now it’s just to configure the binding between a MySettingsConfiguration instance and the configuration section using the Bind method, check it out,
  1. [ApiController]  
  2. [Route("[controller]")]  
  3. public class Way4Controller : ControllerBase  
  4. {  
  5.     private readonly MySettingsConfiguration _settings;  
  6.    
  7.     public Way4Controller(  
  8.         IConfiguration configuration)  
  9.     {  
  10.         _settings = new MySettingsConfiguration();  
  11.         configuration.GetSection("MySettings").Bind(_settings);  
  12.     }  
  13.    
  14.     [HttpGet]  
  15.     public bool Get()  
  16.     {  
  17.         return _settings?.Parameters?.IsProduction ?? false;  
  18.     }  
  19. }  
But we are still using the GetSection method, dependency injection of IConfiguration in the controller’s constructor. We can do better than that!
 
#5 AppSettings – IOptions
 
The next way to read the AppSettings.JSON file is by using the IOptions interface typing MySettingsConfiguration class that we created before.
  1. [ApiController]  
  2. [Route("[controller]")]  
  3. public class Way5Controller : ControllerBase  
  4. {  
  5.     private readonly IOptions<MySettingsConfiguration> _configuration;  
  6.    
  7.     public Way5Controller(  
  8.          IOptions<MySettingsConfiguration> configuration)  
  9.     {  
  10.         _configuration = configuration;  
  11.     }  
  12.    
  13.     [HttpGet]  
  14.     public bool Get()  
  15.     {  
  16.         return _configuration.Value?.Parameters?.IsProduction ?? false;  
  17.     }  
  18. }  
Remember, to use it that way it’s necessary to perform a small configuration on the Startup.cs file. 
  1. public void ConfigureServices(  
  2.     IServiceCollection services)  
  3. {  
  4.     // Way 5  
  5.     services.Configure<MySettingsConfiguration>(Configuration.GetSection("MySettings"));  
  6.    
  7.     services.AddControllers();  
  8. }   
That is a better way to read the AppSettings.JSON file, but we are still using an ASP.NET CORE internal interface, in this case, the IOptions interface.
 
It could be interesting that all controllers and business classes don’t use ASP.NET CORE internal references. 
 
#6 AppSettings – PRE-Binding
 
In my option, the best way to read the AppSettings.JSON file is to injection the MySettingsConfiguration class that we created before.
  1. [ApiController]  
  2. [Route("[controller]")]  
  3. public class Way6Controller : ControllerBase  
  4. {  
  5.     private readonly MySettingsConfiguration _configuration;  
  6.    
  7.     public Way6Controller(  
  8.         MySettingsConfiguration configuration)  
  9.     {  
  10.         _configuration = configuration;  
  11.     }  
  12.    
  13.     [HttpGet]  
  14.     public bool Get()  
  15.     {  
  16.         return _configuration.Parameters.IsProduction;  
  17.     }  
  18. }   
This way is much more straightforward, and we don’t use any ASP.NET CORE internal interface.
 
To make this work, it’s necessary one configuration is in the Startup.cs file. 
  1. public void ConfigureServices(  
  2.      IServiceCollection services)  
  3.  {  
  4.      // Way 6  
  5.      var mySettings = new MySettingsConfiguration();  
  6.      new ConfigureFromConfigurationOptions<MySettingsConfiguration>(Configuration.GetSection("MySettings")).Configure(mySettings);  
  7.      services.AddSingleton(mySettings);  
  8.    
  9.      services.AddControllers();  
  10.  }  
That configuration seems too complex to understand, even more, if you need to repeat that code for other tags and classes.
 
To make it easy and not repeat any code, I created an Extension Method to encapsulate all these code blocks, and it becomes very easy to use it. 
  1. public void ConfigureServices(  
  2.      IServiceCollection services)  
  3.  {              
  4.      // Way 6 extesion  
  5.      services.AddConfiguration<MySettingsConfiguration>(Configuration, "MySettings");  
  6.    
  7.      services.AddControllers();  
  8.  }  
  1. public static class ConfigurationExtension  
  2. {  
  3.     public static void AddConfiguration<T>(  
  4.         this IServiceCollection services,  
  5.         IConfiguration configuration,  
  6.         string configurationTag = null)  
  7.         where T : class  
  8.     {  
  9.         if (string.IsNullOrEmpty(configurationTag))  
  10.         {  
  11.             configurationTag = typeof(T).Name;  
  12.         }  
  13.    
  14.         var instance = Activator.CreateInstance<T>();  
  15.         new ConfigureFromConfigurationOptions<T>(configuration.GetSection(configurationTag)).Configure(instance);  
  16.         services.AddSingleton(instance);  
  17.     }  
  18. }  
That’s it, thank you for reading, and I hope you enjoyed it.
 
Share and comment if you know other ways to read settings the AppSettings.JSON file.
 
Thank you 🙂


Similar Articles