Skip to content

ConfigurationBinder Source Generator is comparing configuration keys case-sensitively #88112

@eerhardt

Description

@eerhardt

Description

The ConfigurationBinder Source Generator is generating code like this:

            foreach (IConfigurationSection section in configuration.GetChildren())
            {
                switch (section.Key)
                {
                    case "ConnectionString":
                        {
                            obj.ConnectionString = configuration["ConnectionString"]!;
                        }
                        break;
                    case "JwtSigningKey":
                        {
                            obj.JwtSigningKey = configuration["JwtSigningKey"]!;
                        }
                        break;

This is not correct because it is comparing the section's Key with "ConnectionString" in a case sensitive manner. However, configuration keys are case-insensitive. This causes setting environment variables like APPSETTINGS__CONNECTIONSTRING to no longer bind correctly.

You can see this happening in the debugger below:

image

Reproduction Steps

Write an app with an options class like:

internal class AppSettings
{
    public required string ConnectionString { get; set; }

    public string? JwtSigningKey { get; set; }

    public bool SuppressDbInitialization { get; set; }
}

During app startup, bind the AppSettings to the configuration like (ensure you are using EnableConfigurationBindingGenerator=true):

    public static IServiceCollection ConfigureAppSettings(this IServiceCollection services, IConfigurationRoot configurationRoot, IHostEnvironment hostEnvironment)
    {
        services.AddSingleton<IValidateOptions<AppSettings>, AppSettingsValidator>()
            .AddOptions<AppSettings>()
            .BindConfiguration(nameof(AppSettings))
            .ValidateOnStart();

Run the app with an environment variable set: $env:APPSETTINGS__CONNECTIONSTRING="Server=127.0.01;User Id=benchmarkdbuser;Password=benchmarkdbpass;Database=postgres".

Expected behavior

The environment variable configuration should bind successfully. The AppSettings object should get its ConnectionString property set to the above.

Actual behavior

The environment variable fails to bind correctly. The ConnectionString property is left empty.

Regression?

This is a regression from the reflection based ConfigurationBinder.

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions