As software developers, we certainly like some configurable options, especially when it allows us to change the behavior of our applications without having to modify or compile our applications. Whether you use a new one or an old one. NET, you may want to leverage the configuration of a JSON file. In this article, we’ll explore the necessary steps to read the configuration and use these values.

Configuration history of.NET

For those ASP.NET veterans, you may remember Wen.config. While it hasn’t been completely abandoned, it plays a less important role in ASP.NET Core. Web. config is an XML-based file used to configure the IIS host environment. In this file, we can place application Settings, load additional Web modules, register handlers, and so on.

Another limitation is that changes to web.config will force the application to restart. Changes can be as simple as adding new application Settings or as complex as adding a new module to the request pipeline. ASP.NET applications must be reloaded to ensure logical consistency. Developers can access all Settings through the ConfigurationManager. Frankly, over time, developers see reboots as a feature, not a hindrance, and use them to reset applications that have fallen into a failed state.

Current ASP.NET Core configuration

ASP.NET Core sees major issues around configuration and tries to improve them for developers in three ways:

  • In addition to XML, other configuration formats are supported.
  • Replace the ConfigurationManager with a friendlier approach to dependency injection (DI).
  • Configuration hot changes can occur immediately in the code being accessed.

These changes reflect more advanced setups and are more friendly to local cloud Web applications. Application configuration can come from multiple locations, and extensibility makes it easier for developers to avoid custom solutions.

With.NET adopting async/await and asynchronous programming, using singletons can cause deadlocks and performance overhead. Making DI configurable gives developers more ways to use set dependencies and decouple these data from any source. It can also test configuration Settings without accessing ConfigurationManager or web.config.

Cold starts are the enemy of all users and can create a frustrating experience. The ability to make changes without a reboot ensures a better run time experience.

Let’s look at the code

So far, we’ve discussed the history and current state of configuration, but let’s skip to actual use.

The first step is to create a data class that reads the Settings from the configuration provider. ASP.NET Core provides several out-of-the-box capabilities, but the most commonly used is the JSON configuration provider. The class needs to contain the same structure as the JSON part.

public class HelloWorldOptions{ public string Text { get; set; }}Copy the code

The next section explains how ASP.NET Core binds the HelloWorldOptions class. We can do this using the BindConfiguration method.

public void ConfigureServices(IServiceCollection services){
    services.AddOptions<HelloWorldOptions>()
            .BindConfiguration("HelloWorld");
}
Copy the code

The string HelloWorld represents part of the appSettings. json file.

{
  "HelloWorld" : {
    "Text": "Hello, Khalid!"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
Copy the code

Good, now we’re ready to use our configuration information. And then it gets a little confusing. We have three interfaces to choose from:

  • IOptions
  • IOptionsSnapshot
  • IOptionsMonitor

Each interface wraps our configuration data and gives us a slightly different life cycle.

IOptions< T> is registered as a singleton, so all values are retrieved once and stored in the ASP.NET Core application’s memory. This method cannot read any updated configuration after the application is started. Registering as a singleton means that ASP.NET can inject the interface into any dependency without worrying about catching it or causing a memory leak. This version is probably the one most people will use.

IOptionsSnapshot< T> has a scoped lifetime. ASP.NET Core rechecks each HTTP request.

An instance of each request is cached until the user receives the response. This approach is useful for those who want to change the configuration dynamically but still need to refresh requests through the current pipeline. This version facilitates the use of switch configurations without reloading the application.

Finally, the IOptionsMonitor< T> is similar to the IOptionsSnapshot but is a singleton life cycle. The IOptionsMonitor method is useful for critical data changes that should be handled immediately. A long-standing back-end service might want to continue receiving configuration changes using IOptionsMonitor without incurring expensive object creation costs.

Now that we know the advantages of each interface, we can use our configuration. In the Configure method found at startup, let’s add a new GET endpoint.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
​
    app.UseRouting();
​
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            var options = 
                context
                    .RequestServices
                    .GetRequiredService<IOptionsSnapshot<HelloWorldOptions>>()
                    .Value;
            
            await context.Response.WriteAsync(options.Text);
        });
    });
}
Copy the code

Notice that in our code, we use IOptionsSnapshot. Passing the instance will allow us to update the configuration without having to restart our application. When we start the application, we should see the configuration values. Changing the configuration changes the result of the request.

{
  "HelloWorld" : {
    "Text": "Hello, World!"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
Copy the code

After reloading, we now see:

Hello, World!
Copy the code

This works, and we don’t have to pay startup costs for minor changes in configuration.

conclusion

Using the configuration in ASP.NET Core can be confusing at first. The Microsoft documentation has a detailed explanation of the IOption interface. Most of the time, people should use IOptions because it’s probably the best performance. That said, if we want the ability to hot load Settings, and if we want consistency, IOptionsSnapshot is the best.

Finally, if your application relies heavily on singleton lifetime and still needs hot loading Settings, consider IOptionsMonitor.

Welcome to pay attention to my public number – code non translation station, if you have a favorite foreign language technical articles, you can recommend to me through the public number message.