Divergic.Configuration.Autofac 1.6.0

Suggested Alternatives

Neovolve.Configuration.DependencyInjection

Additional Details

The Neovolve.Configuration.DependencyInjection package adds this support directly to IHostBuilder without Autofac. It also provides support for hot-reloading.

There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Divergic.Configuration.Autofac --version 1.6.0                
NuGet\Install-Package Divergic.Configuration.Autofac -Version 1.6.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Divergic.Configuration.Autofac" Version="1.6.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Divergic.Configuration.Autofac --version 1.6.0                
#r "nuget: Divergic.Configuration.Autofac, 1.6.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Divergic.Configuration.Autofac as a Cake Addin
#addin nuget:?package=Divergic.Configuration.Autofac&version=1.6.0

// Install Divergic.Configuration.Autofac as a Cake Tool
#tool nuget:?package=Divergic.Configuration.Autofac&version=1.6.0                

Introduction

The Divergic.Configuration.Autofac NuGet package provides an Autofac module for registering nested application configuration types. This is helpful when wanting dependency injection of strong typed application configuration.

GitHub license   Nuget   Nuget

Actions Status

Installation

The package can be installed from NuGet using Install-Package Divergic.Configuration.Autofac.

Usage

There are two ways this package can be used to load application configuration.

  1. Automatically resolve from host configuration
  2. Provide specific configuration resolution

Host configuration

Most modern .Net applications will have their configuration based on IConfiguration that is loaded automatically via WebApplication.CreateBuilder(args) or Host.CreateDefaultBuilder(). In these cases the application configuration is loaded into ServicesCollection which can be ported over to Autofac using the Autofac.Extensions.DependencyInjection package.

This package supports automatically binding your application configuration to your custom application configuration types and configuring the Autofac container with those types.

Consider the following JSON configuration.

{
  "Storage": {
    "Database": "database connection string",
    "BlobStorage": "blob storage connection",
    "TableStorage": "table storage connection"
  },
  "FirstJob": {
    "Name": "My job",
    "TriggerInSeconds": 60
  }
}

This configuration can be represented using the following configuration classes.

public interface IConfig
{
    FirstJob FirstJob { get; }
    Storage Storage { get; }
}

public class Config : IConfig
{
    public FirstJob FirstJob { get; set; }
    public Storage Storage { get; set; }
}

public interface IFirstJob
{
    string Name { get; }
    TimeSpan Trigger { get; }
}

public class FirstJob : IFirstJob
{
    public string Name { get; set; }
    public TimeSpan Trigger => TimeSpan.FromSeconds(TriggerInSeconds);
    public int TriggerInSeconds { get; set; }
}

public interface IStorage
{
    string BlobStorage { get; }
    string Database { get; }
    string TableStorage { get; }
}

public class Storage : IStorage
{
    public string BlobStorage { get; set; }
    public string Database { get; set; }
    public string TableStorage { get; set; }
}

Adding HostConfigurationModule<Config> to the container configuration will cause all the configuration types (including interfaces) to be registered with Autofac. Autofac will return those configuration types bound from the application configuration when they are resolved.

using System;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public static class Program
{
    public static async Task Main(string[] args)
    {
        var builder = Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureContainer<ContainerBuilder>(configure =>
            {
                configure.RegisterModule<HostConfigurationModule<Config>>();
            });

        var host = builder.Build();

        await host.StartAsync().ConfigureAwait(false);

        Console.WriteLine("Completed");
    }
}

Configuration Resolution

The ConfigurationModule<T> class relies on an IConfigurationResolver to load the root configuration class. It will then recursively register all properties found on the root configuration using AsSelf as well as AsImplementedInterfaces where implemented interfaces are found.

Json Resolution

The JsonResolver<T> resolver will load the root configuration (of type T) from an appsettings.json file by default. This can be used by ConfigurationModule like the following.

var builder = new ContainerBuilder();

builder.RegisterModule<ConfigurationModule<JsonResolver<Config>>>();

var container = builder.Build();

The JsonResolver class can accept a different filename if the default appsettings.json is not suitable.

var builder = new ContainerBuilder();
var resolver = new JsonResolver<Config>("hostsettings.json");
var module = new ConfigurationModule(resolver);

builder.RegisterModule(module);

var container = builder.Build();

Need environment configuration override support? Use the EnvironmentJsonResolver to merge configuration for a specific environment.

var env = builderContext.HostingEnvironment;
var builder = new ContainerBuilder();

var resolver = new EnvironmentJsonResolver<Config>("appsettings.json", $"appsettings.{env.EnvironmentName}.json");
var module = new ConfigurationModule(resolver);

builder.RegisterModule(module);

var container = builder.Build();

Custom Resolution

Need to resolve a root configuration object from something other than a JSON file? The ConfigurationModule will accept any IConfigurationResolver. You can write any custom resolver and provide it to the module.

Example

The ConfigurationModule<T> class will register each of the nested properties on the Config class with the Autofac container. Given the example above, the following resolutions on the container will be valid.

var builder = new ContainerBuilder();

builder.RegisterModule<ConfigurationModule<JsonResolver<Config>>>();

var container = builder.Build();

container.Resolve<IConfig>();
container.Resolve<Config>();
container.Resolve<IStorage>();
container.Resolve<Storage>();
container.Resolve<IFirstJob>();
container.Resolve<FirstJob>();

Each of these resolutions can now participate in dependency injection for any other class.

Environment Variable Override

Sometimes you need to be able to change a configuration value without having to redeploy the application or change the application configuration file. Just changing the application configuration file can require a redeployment to deliver the change to a target system. This can be done by using the EnvironmentOverride attribute. A common scenario here is Azure Functions which uses Environment Variables via configuration settings in the Azure portal.

The ConfigurationModule class will detect the EnvironmentOverride attribute being defined on a property and will attempt to resolve the value. If the environment variable defined by the attribute exists, has a value and that value can be converted to the property type then the configuration object will be updated with the value of the environment variable before it is registered in Autofac. If any of these conditions are not met then the existing value from the configuration resolver will remain on the object.

public class Storage : IStorage
{
    [EnvironmentOverride("Application.BlobStorageConnection")]
    public string BlobStorage { get; set; }

    [EnvironmentOverride("Application.DatabaseConnection")]
    public string Database { get; set; }

    [EnvironmentOverride("Application.TableStorageConnection")]
    public string TableStorage { get; set; }
}

The advantage of this design is that application configuration can be resolved with a pre-allocation of an environment override that only comes into play when the environment variable has been set.

Environment Variable Mapping

The module can detect if a string property is a reference to an environment variable. In this case it will resolve the configuration value from the environment variable using the same rules as the Environment Variable Override above.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.6.1-beta0001 83 4/19/2024
1.6.0 2,885 8/14/2023
1.5.2-beta0002 118 8/14/2023
1.5.1 32,000 6/1/2021
1.5.1-beta0001 256 6/1/2021
1.5.0 674 5/30/2021
1.5.0-beta0004 307 5/30/2021
1.4.2-beta0003 309 5/30/2021
1.4.2-beta0001 304 5/30/2021
1.4.1 545 5/2/2021
1.4.1-beta0002 283 5/2/2021
1.4.1-beta0001 256 5/2/2021
1.3.0 3,587 11/13/2020
1.2.1-beta0010 274 11/13/2020
1.2.1-beta0006 266 11/13/2020
1.2.1-beta0003 265 11/13/2020
1.2.1-beta0001 290 11/13/2020
1.2.0 1,303 11/12/2020
1.1.3-beta0019 290 11/12/2020
1.1.3-beta0018 305 11/12/2020
1.1.3-beta0017 286 11/12/2020
1.1.3-beta0016 319 11/12/2020
1.1.3-beta0015 307 11/12/2020
1.1.3-beta0010 305 11/12/2020
1.1.3-beta0006 311 11/12/2020
1.1.3-beta0003 316 11/12/2020
1.1.3-beta0001 312 11/12/2020
1.1.2 4,263 1/22/2020
1.1.2-beta0003 490 1/22/2020
1.1.2-beta0002 372 1/12/2020
1.1.2-beta0001 411 1/12/2020
1.1.1 591 12/18/2019
1.1.1-beta0001 408 12/18/2019
1.1.0 533 12/18/2019
1.1.0-beta0003 431 12/18/2019
1.0.2 1,743 10/13/2018
1.0.1 807 9/5/2018
1.0.0 959 6/12/2018
0.1.0-beta0001 744 6/12/2018