From 8db080e3d08d3d5e53c73db7e59f5efd3d2534e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tam=C3=A1s=20Turny=C3=A1nszki?= Date: Mon, 8 Aug 2022 22:31:30 +0200 Subject: [PATCH] Unable to bind Dictionary with key type "Enum" when key string case is different (#71926) Use ignoreCase=true when parsing enum values. Fix #71185 --- .../src/ConfigurationBinder.cs | 3 ++- .../tests/ConfigurationBinderTests.cs | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs index 38dc4aadd42..f8fae6dcb05 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Binder/src/ConfigurationBinder.cs @@ -576,9 +576,10 @@ private static bool CanBindToTheseConstructorParameters(ParameterInfo[] construc { try { - object key = keyTypeIsEnum ? Enum.Parse(keyType, child.Key) : + object key = keyTypeIsEnum ? Enum.Parse(keyType, child.Key, true) : keyTypeIsInteger ? Convert.ChangeType(child.Key, keyType) : child.Key; + var valueBindingPoint = new BindingPoint( initialValueProvider: () => { diff --git a/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/ConfigurationBinderTests.cs b/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/ConfigurationBinderTests.cs index 0731ff20419..9eae194f02c 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/ConfigurationBinderTests.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Binder/tests/ConfigurationBinderTests.cs @@ -491,6 +491,33 @@ public class ByteArrayOptions public byte[] MyByteArray { get; set; } } + public enum TestSettingsEnum + { + Option1, + Option2, + } + + [Fact] + public void EnumBindCaseInsensitiveNotThrows() + { + var dic = new Dictionary + { + {"Section:Option1", "opt1"}, + {"Section:option2", "opt2"} + }; + + var configurationBuilder = new ConfigurationBuilder(); + configurationBuilder.AddInMemoryCollection(dic); + var config = configurationBuilder.Build(); + var configSection = config.GetSection("Section"); + + var configOptions = new Dictionary(); + configSection.Bind(configOptions); + + Assert.Equal("opt1", configOptions[TestSettingsEnum.Option1]); + Assert.Equal("opt2", configOptions[TestSettingsEnum.Option2]); + } + [Fact] public void CanBindIConfigurationSection() { -- GitLab