Skip to content

Commit

Permalink
Unable to bind Dictionary with key type "Enum" when key string case i…
Browse files Browse the repository at this point in the history
…s different (dotnet#71926)

Use ignoreCase=true when parsing enum values.

Fix dotnet#71185
  • Loading branch information
turnyanszki committed Aug 8, 2022
1 parent 11f162a commit 8db080e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -576,9 +576,10 @@ private static void BindConcreteDictionary(
{
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: () =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>
{
{"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<TestSettingsEnum, string>();
configSection.Bind(configOptions);

Assert.Equal("opt1", configOptions[TestSettingsEnum.Option1]);
Assert.Equal("opt2", configOptions[TestSettingsEnum.Option2]);
}

[Fact]
public void CanBindIConfigurationSection()
{
Expand Down

0 comments on commit 8db080e

Please sign in to comment.