.NET Configuration in Depth

Chris Ayers

Chris Ayers

Senior Customer Engineer
Microsoft

Twitter : @Chris_L_Ayers
Mastodon: @Chrisayers@hachyderm.io
LinkedIn: chris-l-ayers
Blog: https://chris-ayers.com/
GitHub: Codebytes

Agenda

  • What is configuration?
  • How does .NET Framework handle configuration?
  • How does .NET and ASP.NET handle configuration?
  • Configuration Providers
  • Configuration Binding
  • The Options Pattern
  • Questions?

What is Configuration?

Settings

  • Retry Times
  • Queue Length

Feature Flags

  • Per User
  • Percentage

Secrets

  • Connection Strings
  • App Registration

When is configuration applied?

Compile Time

Run Time

.NET Framework Configuration

Web.Config

  • Limited to Key-Value string pairs
  • Accessed through a static ConfigurationManager Class
  • Dependency Injection was not provided out of the box
  • Transformation through difficult syntax
    • Slow Cheetah
  • Hard to unit test
  • Easy to leak secrets

XML, Static Classes, and Parsing

.NET Core/5/6/7/8
ASP.NET Configuration

Configuration Providers

center

Order Matters

center

Keys are flattened

Binding a Section

Out of the Box

Console

  • No Configuration

ASP.NET

  • JSON
    • appsettings.json
    • appsettings.{Environment}.json
  • Environment Variables
  • Command Line Variables
  • User Secrets

Configuration Providers

File-based

  • JSON
  • XML
  • INI
  • Key-per-file

Others

  • Environment variables
  • Command-line
  • In-Memory
  • User Secrets
  • Azure Key Vault
  • Azure App Configuration

Json Provider

Xml Provider

Environment Variables

Command Line Variables

Key-per-file

In Memory

DEMOS

The Options Pattern

Interface Segregation Principle (ISP): Scenarios (classes) that depend on configuration settings depend only on the configuration settings that they use.

Separation of Concerns : Settings for different parts of the app aren't dependent or coupled to one another.

An Options Class

  • Must be non-abstract with a public parameterless constructor
  • Contain public read-write properties to bind (fields are not bound)
public class FileOptions
{
    public string FileExtension { get; set; } ="";
    public string OutputDir { get; set; } ="";
    public string TemplateFile { get; set; } ="";
}

Types of IOptions

Singleton Reloading Support Named Option Support
IOptions
Yes No No
IOptionsSnapshot
No Yes Yes
IOptionsMonitor
Yes Yes Yes

DEMOS

Questions?

Contact

Twitter: @Chris_L_Ayers
Mastodon: @Chrisayers@hachyderm.io
LinkedIn: - chris-l-ayers
Blog: https://chris-ayers.com/
GitHub: Codebytes