Tag: Open Source

Automatic Binding of Settings Classes to Configuration

I’ve had the idea to do this for a while now. It usually pops back into my head when I start a new project and I have to read configuration information into the application. Microsoft’s IOptions<T> is nice, but there is still a bit of ceremony in having to bind each class to it’s configuration in Startup.cs. It seemed like I should just be able to tell the system in some light-weight, unobtrusive way where to get this configuration from and be done with it.

The Dream

So what is this magical “light-weight, unobtrusive way” you speak of? Well, I’m glad you asked! My thought was to create a NuGet package so that I could just plug it into any project, add an attribute to my settings class(es), and set a single constructor parameter that was the section of the configuration to bind it to. Something like this:

    [AutoBind("Features")]
    public class Features
    {
        public bool IsCoolFeatureEnabled { get; set; }
        public int CoolFeatureCount { get; set; }
        public bool IsUberFeatureEnabled { get; set; }
        public bool IsSecretFeatureEnabled { get; set; }
    }

In my magical world that should automatically bind to a section in my configuration named “Features”.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "Features": {
    "IsCoolFeatureEnabled": true,
    "CoolFeatureCount": 4,
    "IsUberFeatureEnabled": true,
    "IsSecretFeatureEnabled": false 
  },
  "AllowedHosts": "*"
}

Then, for example, I could inject an instance of “Features” into a controller and use them to control the availability of features in my application (for example). In this case I’m just going to pass the settings (“Features”) to my view to control the layout of the page like so:

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly Features _features;

        public HomeController(ILogger<HomeController> logger, Features features)
        {
            _logger = logger??throw new ArgumentNullException(nameof(logger));
            _features = features ?? throw new ArgumentNullException(nameof(features));
        }

        public IActionResult Index()
        {
            return View(_features);
        }

        ...
    }

The Startup Code (“The Glue”)

The only “glue” to hold all this together is a little one-liner in the Startup.cs file’s ConfigureServices method, that you only have to make once. You don’t have to go back to the startup each time you want to configure a new class for configuration settings.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoBoundConfigurations(Configuration).FromAssembly(typeof(Program).Assembly);
        services.AddControllersWithViews();
    }

The AddAutoBoundConfigurations(…) method sets up a builder with your configuration root. Each time you call FromAssembly(…) using the fluent API it will scan that assembly for any classes with the AutoBind attribute, create an instance, bind it to your configuration, and configure it as a singleton for dependency injection.

The fluent API also exposes a Services property which will allow you to chain back into the services fluent API to continue your setup if you wish to like this.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoBoundConfigurations(Configuration)
                .FromAssembly(typeof(Program).Assembly)
                .Services
                .AddControllersWithViews();
    }

Wrapping it up – Back to the View

I’ve created a view that uses the “Features” settings to enable features (OK, they’re just div tags on the page, but you get the idea.) and to control the number of CoolFeatures that are on the page. Here’s the razor view:

@model AutoBind.Demo.Settings.Features
@{
    ViewData["Title"] = "Home Page";
}
    <div class="row">
        <div class="col-sm-12 mb-5">
            <h1 class="text-4">Features</h1>
        </div>
    </div>
    <div class="row">
    @if (Model.IsCoolFeatureEnabled)
    {
        @for (int index = 1; index <= Model.CoolFeatureCount; index++)
        {
            <div class="col-sm-4">
                <div class="card text-white bg-info mb-3">
                    <div class="card-header">Cool Feature # @index</div>
                    <div class="card-body">
                        <p class="card-text">Here's my cool feature!</p>
                    </div>
                </div>
            </div>
        }
    }
    @if (Model.IsUberFeatureEnabled)
    {
        <div class="col-sm-4">
            <div class="card text-white bg-dark mb-3">
                <div class="card-header">Uber Feature</div>
                <div class="card-body">
                    <p class="card-text">Here's my uber feature!</p>
                </div>
            </div>
        </div>
    }
    @if (Model.IsSecretFeatureEnabled)
    {
        <div class="col-sm-4">
            <div class="card text-white bg-warning mb-3">
                <div class="card-header">Secret Feature</div>
                <div class="card-body">
                    <p class="card-text">Here's my secret feature!</p>
                </div>
            </div>
        </div>
    }
    </div>

Here’s what the rendered page looks like in the browser:

Screenshot

Summary

This is a simple example, but in larger projects with lots of configuration its nice to be able to quickly create and use your configuration settings classes without having to deal with the plumbing.

The package is available on NuGet.org. You can install it in your projects from Visual Studio by searching for the package DotNetNinja.AutoBoundConfiguration or install it from the command line with:

dotnet add package DotNetNinja.AutoBoundConfiguration

The source is available on GitHub @ https://github.com/DotNet-Ninja/DotNetNinja.AutoBoundConfiguration.