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 What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos