Tag: NuGet

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.

Configuring a Custom NuGet Feed in Visual Studio

Configuring a custom NuGet feed in Visual Studio couldn’t really be any simpler.  For example, I have a custom feed hosted on MyGet.org that hosts the CI nugget builds for my open source projects.   To configure Visual Studio to use it just go to the Tools|Options in the menu and then expand the NuGet Package Manager node on the left side of the dialog and select Package Sources.

NuGet Feed Settings

Next click the + button in top right to add a new entry, select the new item in the list of available package sources, change the name and the source and click update.

That’s it, now your all set to pull in packages from your new feed.

Microsoft Releases ASP.NET MVC 3.0, IIS Express, SQL Server Compact Edition 4.0, WebMatrix and more…

About a week ago (January 13th, 2011) Microsoft released a slew of developer tools to the web.

IIS Express 7.5

This is the item I am most excited about.  IIS Express is a free version of IIS 7.5 that can be used by developers when building web site.  It’s somewhere between Cassini (the ASP.Net development server) and a full blown IIS 7.5 install.  It provides support for SSL, URL Rewriting, and other IIS 7.x modules, while remaining under a 5mb download and running under non-administrator accounts.  It runs on Windows XP and higher and will run side by side with a full IIS install or Cassini.

Visual Studio 2010 SP1 (currently in Beta) will add support in Visual Studio for setting IIS Express as your default development server.

You can download IIS Express 7.5 and run it without SP1 for Visual Studio if you wish, but you will need to manually start the server.

Related Blog Posts:

Scott Guthrie: Introducing IIS Express

Scott Guthrie: VS 2010 SP1 (Beta) and IIS Express

ASP.NET MVC 3.0

Asp.Net MVC 3.0 is a very large release including:

  • The new ‘Razor’ View Engine which minimizes the number of characters used in you mark-up when data binding.
  • Improved JavaScript support.
  • Improved Validation.
  • Partial page output caching.
  • Better support for Dependency Injection and IOC Containers.

Get your hands dirty by downloading ASP.NET MVC 3.0 and trying out some demos on http://www.asp.net/mvc/.

NuGet

Nuget is a free, open source package manager that makes it easy for .NET developers to include open source libraries in any type of project from ASP.Net Web Forms to WPF.

Get the installer @ nuget.org and get started using all that open source goodness like NUnit, NHibernate, Castle.Windsor, and more.

Get more info:

Scott Hanselman’s Blog

Scott Guthrie’s Blog