Skip to content

Breaking change in environment variable configuration prefix support in dotnet 6 #61577

@matt-richardson

Description

@matt-richardson

Description

When using environment variable configuration, the prefix is no longer normalized like it was in dotnet 5.0.

As the environment variable prefix should contain : if on Windows, and __ if on Linux, then normalizing the prefix makes sense to me. Otherwise, I have to duplicate the OS detection/normalization code myself.

Reproduction Steps

  1. Create a new console app
  2. Add references to Microsoft.Extensions.Configuration, Microsoft.Extensions.Configuration.Binder and Microsoft.Extensions.Configuration.EnvironmentVariables
  3. Add the following code
using System;
using Microsoft.Extensions.Configuration;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var environmentOverridesPrefix = typeof(Program).Namespace!.Replace(".", ":") + ":";

            var configuration = new ConfigurationBuilder()
                .AddEnvironmentVariables(environmentOverridesPrefix)
                .Build();

            var appSettings = new AppSettings();
            configuration.Bind(appSettings);

            Console.WriteLine(appSettings.Foo ?? "<null>");
        }
    }

    public class AppSettings
    {
        public string? Foo { get; set; }
    }
}
  1. Set an environment variable ConsoleApp1__Foo=42

Expected behavior

It should print 42

Actual behavior

It prints <null>

Regression?

This works in dotnet 5.0.

Known Workarounds

Changing the prefix to use __ instead of : works:

eg, if I change the line
var environmentOverridesPrefix = typeof(Program).Namespace!.Replace(".", ":") + ":";
to
var environmentOverridesPrefix = typeof(Program).Namespace!.Replace(".", "__") + "__";
it works

Configuration

.NET version: 6.0.100
OS: Windows 11, 21H2 (OS Build 22000.346)
Arch: x64
Platform specific: no, we were facing it on linux as well

Other information

It appears that 9a322a5 changed the behavior as part of #42932 while trying to fix #40911.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions