Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ConfigurationBinder.Bind on virtual properties duplicates elements #70592

Merged
merged 7 commits into from
Jun 14, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -757,11 +757,30 @@ private static List<PropertyInfo> GetAllProperties(
Type type)
{
var allProperties = new List<PropertyInfo>();
HashSet<string>? propertyNames = null;

Type? baseType = type;
do
{
allProperties.AddRange(baseType!.GetProperties(DeclaredOnlyLookup));
PropertyInfo[] baseTypeProperties = baseType!.GetProperties(DeclaredOnlyLookup);
eerhardt marked this conversation as resolved.
Show resolved Hide resolved

if (baseType != type)
{
foreach (var property in baseTypeProperties)
{
if (propertyNames!.Add(property.Name))
{
allProperties.Add(property);
}
}
}
else
{
propertyNames = new(baseTypeProperties.Select(mp => mp.Name),
StringComparer.Ordinal);
allProperties.AddRange(baseTypeProperties);
}

baseType = baseType.BaseType;
}
while (baseType != typeof(object));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1750,6 +1750,21 @@ public void CanBindNullableNestedStructProperties()
Assert.True(bound.NullableNestedStruct.Value.DeeplyNested.Boolean);
}

[Fact]
public void CanBindVirtualPropertiesWithoutDuplicates()
{
ConfigurationBuilder configurationBuilder = new();
configurationBuilder.AddInMemoryCollection(new Dictionary<string, string>
{
{ "Test:0", "1" }
});
IConfiguration config = configurationBuilder.Build();

var test = new ClassOverridingVirtualProperty();
config.Bind(test);
Assert.Equal("1", Assert.Single(test.Test));
}


private interface ISomeInterface
{
Expand Down Expand Up @@ -1827,5 +1842,15 @@ public struct DeeplyNested
public bool Boolean { get; set; }
}
}

public class BaseClassWithVirtualProperty
{
public virtual string[] Test { get; set; } = System.Array.Empty<string>();
}

public class ClassOverridingVirtualProperty : BaseClassWithVirtualProperty
{
public override string[] Test { get => base.Test; set => base.Test = value; }
}
}
}