Configuration - mcbride-clint/DeveloperCurriculum GitHub Wiki

Microsoft introduced a new way to handle configuration entries to be less windows specific and extendable.
A ConfigurationBuilder object allows you to add ConfigurationProvider objects that will assemble all found entries in a Configuration object. Providers that are added last take priority and will override entries that are added earlier.

Configuration providers read configuration data from key-value pairs using a variety of configuration sources:

  • Settings files, such as appsettings.json
  • Environment variables
  • Azure Key Vault
  • Azure App Configuration
  • Command-line arguments
  • Custom providers, installed or created
  • Directory files
  • In-memory .NET objects

appsettings.json

Default configuration values are stored in an appsettings.json file in json format.

Example File:


{
  "Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  },
  "MyKey":  "My appsettings.json Value",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Accessing Configuration Data

Once a ConfigurationBuilder object is built, it will produce a Configuration. This will need to be either retained or injected into other classes through Dependency Injection.

Creating configuration through a HostBuilder, the configuration object will be added to your services collection as a ICollection object. The configuration entries, are then accessed as an array of key value pairs.


public class TestModel : PageModel
{
    // requires using Microsoft.Extensions.Configuration;
    private readonly IConfiguration Configuration;

    public TestModel(IConfiguration configuration) // Injected configuration object
    {
        Configuration = configuration;
    }

    public ContentResult OnGet()
    {
        var myKeyValue = Configuration["MyKey"];
        var title = Configuration["Position:Title"];
        var name = Configuration["Position:Name"];
        var defaultLogLevel = Configuration["Logging:LogLevel:Default"];


        return Content($"MyKey value: {myKeyValue} \n" +
                       $"Title: {title} \n" +
                       $"Name: {name} \n" +
                       $"Default Log Level: {defaultLogLevel}");
    }
}

Values can also be retrieved via a `.GetValue<T>(key)` method.
This method will get the value that matches the key and converts it to the given `T` type.

Options

Complex configuration objects can also be mapped to a class and it's properties.


// appsettings.json
 "Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  }

// Options 
public class PositionOptions
{
    public const string Position = "Position";

    public string Title { get; set; }
    public string Name { get; set; }
}

// Binding a configuration object to an Options Object
public class Test21Model : PageModel
{
    private readonly IConfiguration Configuration;
    public PositionOptions positionOptions { get; private set; }

    public Test21Model(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public ContentResult OnGet()
    {            
        positionOptions = Configuration.GetSection(PositionOptions.Position)
                                                     .Get<PositionOptions>();

        return Content($"Title: {positionOptions.Title} \n" +
                       $"Name: {positionOptions.Name}");
    }
}

You can also bind an Options object at startup and inject it when needed.


public void ConfigureServices(IServiceCollection services)
{
    services.Configure<PositionOptions>(Configuration.GetSection(
                                        PositionOptions.Position));
    services.AddRazorPages();
}

public class Test2Model : PageModel
{
    private readonly PositionOptions _options;

    public Test2Model(IOptions<PositionOptions> options)
    {
        _options = options.Value;
    }

    public ContentResult OnGet()
    {
        return Content($"Title: {_options.Title} \n" +
                       $"Name: {_options.Name}");
    }
}

See Also