# .NET Configuration

The configuration system depends on configuration providers - the sources of configuration data.

# Options

services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));

The IOptions<T> instance is registered as a singleton.

Reloading

To support configuration providers that can be reloaded during runtime, we can inject IOptionsSnapshot<T> instead of IOptions<T>.

The class for out options needs to have properties that:

  • are public
  • have getters
  • have setters (or non-null value if complex type)
  • are not indexers

IEnumerable

An IEnumerable<T> property that is initialized cannot be bound to. That's becasue IEnumerable<T> does not have the Add method.

# Lambda

We are able to customize Options in runtime:

services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));
services.Configure<MyOptions>(options => 
{
    options.Mode = Modes.Mode1;
});

The configuration system executes both operations. First, the IConfiguration is read and then Mode property is overwritten.

# Without Options

# Nuget packages:

  • Microsoft.Extensions.Configuration;
  • Microsoft.Extensions.Configuration.Files.Json
  • Microsoft.Extensions.Configuration.Binder

# Building

private static AppConfiguration GetConfiguration()
{
    var rawConfig = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();

    return ConfigurationBinder.Get<AppConfiguration>(rawConfig);
}
Last Updated: 10/5/2022, 6:26:29 PM