info@clear-measure.com (512) 298-1232

March 7, 2017 | Eric Fleming @efleming18 | Blog


For this article, I’m using Visual Studio 2017 RC along with the .NET Core SDK RC4.

With ASP.NET Core, the way you configure your application has seen significant changes and improvements. When dealing with larger solutions, we often end up having an <applicationSettings> section in our App.Config, Web.Config, or even several across many projects, all of which needed the same settings with the same values. Seems a little redundant doesn’t it? What about multiple configuration sources? Or the need to overwrite values when our application is running in different environments?

In an “out of the box” ASP.NET Core Web Application (.NET Core) template, we’re started with the basics of everything we need to hit the ground running, easily configuring our system as needed for the context in which it’s run.

Diving Into The Default Project

You’ll notice this right away in the constructor of the Startup.cs of the web project, shown below.

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

Quickly reviewing this

  • SetBasePath will set the base path where we want to look for our json files, which will default to the current root directory.
  • Providers for JSON files containing our settings and their values are added, each one overwriting the values from previous providers should they contain the same keys
  • The first **appsettings.json** file is where you can store general settings and their values that are not sensative in nautre and add placeholders to help document the expected key/value pairs your application needs
  • You can alternately store files as user secrets (which is the topic for another post), such as your Azure credentials or sensative API keeys. These types of settings shouldn’t be checked in to your repo
  • We can also add Environment variables, which are added last in our code sample, and they again overwrite any previously loaded values

Note: These configuration sources will be read in the order they are specified.

Accessing Configuration Values in ASP.NET Core

Now that loading our configuration sources is complete, we can see how to actually access the values stored in those providers and use them in our application. To demonstrate this, let’s take an example of using multiple feature toggles throughout our app. The first step would be to create a new class called **FeatureToggles.cs** and add our expected feature toggles to it.

        namespace Web
        {
            public class FeatureToggles
            {
                public bool FeatureToggle1 { get; set; }
                public bool FeatureToggle2 { get; set; }
                public bool FeatureToggle3 { get; set; }
            }
        }

Let’s add what we expect these values to be set to in our appsettings.json file.

    "FeatureToggles": {
        "FeatureToggle1": true,
        "FeatureToggle2": false,
        "FeatureToggle3": true
    }

Great! We have these values in appsettings.json, but how do we extract them in Startup? Easy.

In our ConfigureServices method, we’ll need to add the following:

    services.Configure(Configuration.GetSection("FeatureToggles"));

What this will do, is actually build a FeatureToggles object to be used elsewhere…but how do we inject that object throughout the app? Also easy.

Using the Options Pattern

We can accomplish injecting these settings elsewhere using the Options pattern which uses custom classes, in our case the FeatureToggles class, to represent a group of strongly typed, related settings.

To enable the Options pattern, all we need to do is add the following line to our ConfigureServices method.

    services.AddOptions();

Using the Values at Runtime

Now, the FeatureToggles object we build from our appsettings.json file will be available to us in our Web app via dependency injection!
Let’s use these FeatureToggles in our HomeController. All we need to do is add a constructor which accepts the configuration object via an IOptions parameter.

        public HomeController(IOptions featureToggles)
        {
            //A FeatureToggles object that contains all 3 FeatureToggles with their values 
            var toggles = featureToggles.Value;

            //Gets specifically the value for FeatureToggle1
            var featureToggle1 = featureToggles.Value.FeatureToggle1;
        }

Note that using IOptions<> will bring in the following `using` statement:

    using Microsoft.Extensions.Options;

When the runtime creates an instance of the controller, the IOptions<> dependency will be built up using the settings from our configuration section and injected into the controller’s constructor. We will then have access to all values associated with the specific configuration class.

Can I Share Configuration Across Projects in My Solution?

When I first started playing around with this new way of configuration I was curious how this would work with other projects. For example, given a solution with a Web application, what if I also created an Infrastructure project which needed to connect to my Azure account? Typcially we would have to create an App.config file, add the element to it and wire it up from our Web application. Now with the IOptions pattern, it will essentially be the same as what we did above the our HomeController. No new App.config, no duplication of settings, just injecting IOptions<> is enough to access the settings across projects! This also has the additional benefit of making it easy to test.

That’s it! That’s how you can configure your environment to pull settings from the appsettings.json files and use them throughout your application.

Next Steps

A reference that will undoubtedly help you out if you want to dive deeper into certain aspects of configuration can be found below:
Microsoft Docs – Configuration in ASP.NET Core

Author: Eric Fleming