ASP.NET Core 2.0 Configuration

Problem

How do we read configuration settings from various sources and use them throughout our application?

Solution

Starting from the Empty Project from a previous post, add appsettings.json and appsettings.Development.json files in your project.

  1. // appsettings.json  
  2. {  
  3.   "Section1": {  
  4.     "SettingA""ValueA",  
  5.     "SettingB""ValueB"  
  6.   },  
  7.   "Section2": {  
  8.     "SettingC""ValueC"  
  9.   }  
  10. }  
  11. // appsettings.Development.json  
  12. {  
  13.   "Section1": {  
  14.     "SettingA""Dev_ValueA"  
  15.   },  
  16.   "Section2": {  
  17.     "SettingC""Dev_ValueC"  
  18.   }  
  19. }  

Then, read configuration settings in the constructor for Startup class.

  1. public static IConfiguration Config { get; private set; }  
  2.   
  3. public Startup(  
  4.     IConfiguration config)  
  5. {  
  6.     Config = config;  
  7. }  

Then, add option services in ConfigureServicees() method of Startup class.

  1. public void ConfigureServices(  
  2.     IServiceCollection services)  
  3. {  
  4.     // setup dependency injection in service container  
  5.     services.AddOptions();  
  6.     services.Configure(Config);  
  7. }  

Finally, inject settings as IOptions interface where T is your POCO.

  1. public class HelloWorldMiddleware  
  2. {  
  3.     private readonly RequestDelegate next;  
  4.     private readonly AppSettings settings;  
  5.   
  6.     public HelloWorldMiddleware(  
  7.         RequestDelegate next,  
  8.         IOptions options)  
  9.     {  
  10.         this.next = next;  
  11.         this.settings = options.Value;  
  12.     }  
  13.   
  14.     public async Task Invoke(HttpContext context)  
  15.     {  
  16.         var jsonSettings = JsonConvert.SerializeObject(this.settings);  
  17.         await context.Response.WriteAsync(jsonSettings);  
  18.     }  
  19. }  

Running the sample application gives you the following output.

Discussion

ASP.NET Core has a simple mechanism to read application settings from various sources like JSON file, Environment variables, or even custom data sources. It is also simple to use the settings, thanks to Dependency Injection.

Although it seems like magic (how did your settings get loaded!), ASP.NET Core 2.0 hides the adding of configuration settings behind CreateDefaultBuilder() method of WebHost, in Program.cs. IConfiguration is then added to the service container and is available in the rest of your application. We used this in Startup to add options. To see this, replace the BuildWebHost() method in Program.cs and run the program. You’ll get the same result.

  1. public static IWebHost BuildWebHost(string[] args)  
  2. {  
  3.     return WebHost.CreateDefaultBuilder(args)  
  4.                    .ConfigureAppConfiguration((context, builder) =>  
  5.                    {  
  6.                        var env = context.HostingEnvironment;  
  7.   
  8.                        builder.AddJsonFile("appsettings.json",   
  9.                                     optional: true, reloadOnChange: true)  
  10.                               .AddJsonFile($"appsettings.{env.EnvironmentName}.json",   
  11.                                     optional: true, reloadOnChange: true);  
  12.   
  13.                        if (env.IsDevelopment())  
  14.                        {  
  15.                            var appAssembly = Assembly.Load(  
  16.                                new AssemblyName(env.ApplicationName));  
  17.                            if (appAssembly != null)  
  18.                            {  
  19.                                builder.AddUserSecrets(appAssembly, optional: true);  
  20.                            }  
  21.                        }  
  22.   
  23.                        builder.AddEnvironmentVariables();  
  24.   
  25.                        if (args != null)  
  26.                        {  
  27.                            builder.AddCommandLine(args);  
  28.                        }  
  29.                    })  
  30.                    .UseStartup<Startup>()  
  31.                    .Build();  
  32. }  

In the solution above, two JSON file sources are provided. The important thing to remember is that these sources are read sequentially and overwrite the settings from the previous source. You could see this in the solution above. The output shows Setting B’s value coming from first settings file whereas the other settings are being overwritten by the second settings file.

Note that a public static property holds IConfiguration instance so that it can be used throughout the application like -

  1. var valueA = Config["Section1:SettingA"];  

However, a better approach also exists to read the settings, i.e., to read the settings into a typed POCO class and then inject it as a dependency into middleware, controllers etc. In the solution above, I’ve used the middleware from a previous post to demonstrate this pattern.

You can also have POCO classes for various sections in the settings file and read them using GetSection() method on IConfiguration.

  1. services.Configure(Config.GetSection("Section1"));  

It’s also possible to populate the settings in code using overload of IServiceCollection.Configurethat accepts strongly typed lambda.

  1. services.Configure(options =>  
  2. {  
  3.     options.Section1.SettingA = "SomeValue";  
  4. });  

Source Code

GitHub

Up Next
    Ebook Download
    View all
    Learn
    View all