Take advantage of configuration providers and dependency injection to configure your ASP.Net Core applications in a loosely coupled manner Credit: Gerd Altmann Microsoft’s ASP.Net Core is an open-source, cross-platform, lean, and modular framework for building high-performance, scalable web applications. Configuration data in ASP.Net Core is stored as key-value pairs, and can be organized in a multi-level manner. In this article, we will create a new ASP.Net Core project and then use this project to examine how we can work with configuration data in an ASP.Net Core application. Create a new ASP.Net Core project To create a new ASP.Net Core project, follow the steps outlined below. Note that this post assumes that you have Visual Studio 2017 installed in your system. Open Visual Studio 2017 IDE. Click on File > New > Project. Select “ASP.Net Core Web Application (.Net Core)” from the list of the templates. Specify a name for the project. Click OK. Select “API” in the “New .Net Core Web Application…” window. Select the version of ASP.Net Core you would like to use from the drop-down list at the top. Uncheck the “Enable Docker Support” and “Configure for HTTPS” options. Select “No Authentication” as we won’t be using it either. Click OK. A new ASP.Net Core project will be created. Note that when a new ASP.Net Core project is created, two files — namely, appsettings.json and appsettings.Development.json — will be configured. Another point to note here is that beginning with ASP.Net Core 2.0, configuration data can now be configured in Program.cs. You are no longer constrained to specify configuration data only in the Startup.cs file. Here is how your Program.cs file will look in ASP.Net Core 2.1: public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } Use the JSON configuration provider in ASP.Net Core You can leverage the appsettings.json file to store your configuration data, i.e., your database connection strings or application specific settings. The following code snippet illustrates how you can add the appsettings.json file using the AddJsonFile method of the IConfigurationBuilder instance. public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.SetBasePath(env.ContentRootPath); config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); }) .UseStartup<Startup>(); Now, suppose you have the following content in your appsettings.json file. { "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "CustomKeys": { "KeyA": "ValueA", "KeyB": "ValueB" } } To read values from a configuration file, you need an instance of type IConfiguration. So, if you would like to retrieve the data from the key-value pair of the appsettings.json file in your controller, you should take advantage of dependency injection to inject the IConfiguration instance as shown below. public class ValuesController : ControllerBase { IConfiguration _configuration; public ValuesController(IConfiguration configuration) { _configuration = configuration; } //Other methods } The following code snippet illustrates how you can leverage the IConfiguration instance to read key-value pair data from the CustomKeys section of the appsettings.json file. [HttpGet] public ActionResult<IEnumerable<string>> Get() { var keyA = _configuration["CustomKeys:KeyA"]; var keyB = _configuration["CustomKeys:KeyB"]; return new string[] { keyA, keyB }; } Here is the complete listing of the ValuesController class for your reference. public class ValuesController : ControllerBase { IConfiguration _configuration; public ValuesController(IConfiguration configuration) { _configuration = configuration; } [HttpGet] public ActionResult<IEnumerable<string>> Get() { var keyA = _configuration["CustomKeys:KeyA"]; var keyB = _configuration["CustomKeys:KeyB"]; return new string[] { keyA, keyB }; } } You can also create an additional JSON file to store key-value pairs to be used by the application. In other words, not all of your configuration data must reside in the default appsettings.json. Assuming that you have created a file named customsettings.json, the following code snippet shows how these two JSON files (our customsettings.json file and the appsettings.json file that is created by default) can be added using the builder instance. public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; string pathOfCommonSettingsFile = env.ContentRootPath; config.SetBasePath(env.ContentRootPath); config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); config.AddJsonFile(Path.Combine(pathOfCommonSettingsFile, "customsettings.json"), optional: true); }) .UseStartup<Startup>(); Use the memory configuration provider in ASP.Net Core The memory configuration provider enables you to store and retrieve configuration data without having to use a physical file; the configuration data is stored directly in memory. You can take advantage of the memory provider to store your configuration data as illustrated in the code snippet given below. var builder = new ConfigurationBuilder(); var profileCollection = new Dictionary<string, string> { {"AuthorProfile:FirstName", "Joydip"}, {"AuthorProfile:LastName", "Kanjilal"}, {"AuthorProfile:Address", "Hyderabad, India"} }; builder.AddInMemoryCollection(profileCollection); Configuration = builder.Build(); You can then retrieve the configuration data using the IConfiguration instance in your application as shown in the following code snippet. var firstName = _configuration["Profile:FirstName"]; Note that, contrary to ASP.Net, configuration data in ASP.NET Core applications are not refreshed when the data is changed. However, you can refresh your configuration data in ASP.Net Core in two ways – either by restarting the application or by calling the Reload() method exposed by the IConfigurationRoot interface in the Microsoft.Extensions.Configuration namespace. The Reload() method explicitly reloads the configuration data from the underlying configuration providers. The IConfigurationBuilder interface contains many extension methods that you can use to work with configuration data residing in JSON, XML, or INI files. As we’ve seen, you can even work with in-memory configurations. Related content feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos