Skip to content

Commit c62993f

Browse files
svickCopilot
andauthored
Fix config binding source generator duplicating collection items bound through a constructor parameter (#131092)
## Summary Fixes #83803. The Configuration Binding **source generator** duplicated the items of a collection property that is populated while an instance is created, when binding a type with a parameterized constructor. For example, given: ```csharp internal sealed class Source(string Name, IEnumerable<string> Addresses, IList<int> Ints, string[] Strings) { public string Name { get; } = Name; public IEnumerable<string> Addresses { get; } = Addresses; public IList<int> Ints { get; } = Ints; public string[] Strings { get; } = Strings; } ``` binding `ints: [1, 2, 3, 4, 5]` produced `1, 2, 3, 4, 5, 1, 2, 3, 4, 5`. Arrays and scalars were unaffected; only additive collections (`IList<T>`, `IEnumerable<T>`, settable collections) duplicated. The reflection binder was already fixed (#106158, #129775); this brings the source generator in line. ## Root cause For a type with a parameterized constructor, the generated code first calls `Initialize(...)` - which invokes the constructor and populates the members bound during construction - and then calls `BindCore(...)`, which re-bound **every** property. Re-binding a collection property appends to the collection that was already filled, so the items appear twice. ## Fix The generated `BindCore` method now takes an optional `boundThroughConstructor` parameter, emitted only for parameterized-constructor object types that actually have a re-bindable property bound during construction. Properties bound in `Initialize` are deferred into an `if (!boundThroughConstructor)` block, so they are bound only when the instance was **not** created through `Initialize` (e.g. `config.Bind(existingInstance)`), matching the reflection binder's `BindProperties`/`ResetPropertyValue` behavior. Call sites pass the flag when the instance is (re)created: - `true` for unconditional construction (`var x = Initialize(...)`), - a runtime `wasNull` flag for the `x ??= Initialize(...)` case, since the constructor only runs when the existing value was null, - a runtime flag tracked by the caller for paths that construct the instance separately from `BindCore` (dictionary elements). The fix covers every construct-then-bind path: top-level `Get<T>()`, nested properties (`??=`), dictionary values, and list/array elements. "Bound during construction" means both: - a property that flows through a matching constructor parameter (records, positional or case-mismatched), and - a `required`/`init`-only property assigned in the generated object initializer, even when it has no matching constructor parameter. The latter also fixes a `CS1717` self-assignment (`x = x`) the generator previously emitted for a complex or collection `init`/`required` property in `Initialize`. No baseline `.generated.txt` changes: the extra parameter/guard only appear for the affected type shapes, none of which are in the baseline suite. ## Out of scope Two related, pre-existing source-generator issues surfaced during review and are intentionally left for follow-ups: - #95006 - `CS9035` for a `required` property on a parameterless-constructor type (the generator never emits an object initializer there). - A non-null preset default on an `init` collection is replaced rather than appended to on the `Get<T>()` path (reflection appends). > [!NOTE] > This pull request was authored with the assistance of GitHub Copilot. --------- Co-authored-by: Copilot <[email protected]> Copilot-Session: 1a0d7ac2-f2a3-4526-93ab-36bf1a23933f
1 parent eff9a2f commit c62993f

4 files changed

Lines changed: 385 additions & 30 deletions

File tree

‎src/libraries/Microsoft.Extensions.Configuration.Binder/gen/Emitter/CoreBindingHelpers.cs‎

Lines changed: 173 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -260,10 +260,17 @@ private void EmitBindCoreMethods()
260260
private void EmitBindCoreMethod(ComplexTypeSpec type)
261261
{
262262
string objParameterExpression = $"ref {type.TypeRef.FullyQualifiedName} {Identifier.instance}";
263-
EmitStartBlock(@$"public static void {nameof(MethodsToGen_CoreBindingHelper.BindCore)}({Identifier.IConfiguration} {Identifier.configuration}, {objParameterExpression}, bool defaultValueIfNotFound, {Identifier.BinderOptions}? {Identifier.binderOptions})");
264-
265263
ComplexTypeSpec effectiveType = (ComplexTypeSpec)_typeIndex.GetEffectiveTypeSpec(type);
266264

265+
// Objects created through a parameterized constructor need an extra parameter that tells BindCore
266+
// whether the instance was created through that constructor. When it was, properties that are bound
267+
// by a matching constructor parameter must not be bound again (see EmitBindCoreImplForObject).
268+
string boundThroughConstructorParam = ShouldEmitBoundThroughConstructorParameter(effectiveType)
269+
? $", bool {Identifier.boundThroughConstructor} = false"
270+
: string.Empty;
271+
272+
EmitStartBlock(@$"public static void {nameof(MethodsToGen_CoreBindingHelper.BindCore)}({Identifier.IConfiguration} {Identifier.configuration}, {objParameterExpression}, bool defaultValueIfNotFound, {Identifier.BinderOptions}? {Identifier.binderOptions}{boundThroughConstructorParam})");
273+
267274
switch (effectiveType)
268275
{
269276
case ArraySpec arrayType:
@@ -408,7 +415,8 @@ void EmitBindImplForMember(MemberSpec member)
408415
// Since we're binding to local variables, we can always get and set
409416
canSet: true,
410417
canGet: true,
411-
InitializationKind.None);
418+
InitializationKind.None,
419+
bindingToLocal: true);
412420

413421
if (canBindToMember)
414422
{
@@ -819,11 +827,27 @@ void Emit_BindAndAddLogic_ForElement(string parsedKeyExpr)
819827

820828
if (_typeIndex.CanInstantiate(complexElementType))
821829
{
830+
// A reference-type element created through a parameterized constructor must not have
831+
// its constructor-bound properties bound again. Since the element is only constructed
832+
// when it isn't already present, track that at run time and forward it to BindCore.
833+
// Value-type elements are always (re)constructed through the InitializationKind.None
834+
// path below, so they don't need a separate flag.
835+
string? constructedExpr = null;
836+
if (!isValueType && ShouldEmitBoundThroughConstructorParameter(complexElementType))
837+
{
838+
constructedExpr = GetIncrementalIdentifier(Identifier.boundThroughConstructor);
839+
_writer.WriteLine($"bool {constructedExpr} = false;");
840+
}
841+
822842
EmitStartBlock($"if (!({conditionToUseExistingElement}))");
823843
EmitObjectInit(complexElementType, Identifier.element, InitializationKind.SimpleAssignment, Identifier.section);
844+
if (constructedExpr is not null)
845+
{
846+
_writer.WriteLine($"{constructedExpr} = true;");
847+
}
824848
EmitEndBlock();
825849

826-
EmitBindingLogic();
850+
EmitBindingLogic(constructedExpr);
827851
}
828852
else
829853
{
@@ -832,14 +856,15 @@ void Emit_BindAndAddLogic_ForElement(string parsedKeyExpr)
832856
EmitEndBlock();
833857
}
834858

835-
void EmitBindingLogic()
859+
void EmitBindingLogic(string? constructedExpr = null)
836860
{
837861
this.EmitBindingLogic(
838862
complexElementType,
839863
Identifier.element,
840864
Identifier.section,
841865
InitializationKind.None,
842-
ValueDefaulting.None);
866+
ValueDefaulting.None,
867+
constructedExpr: constructedExpr);
843868

844869
_writer.WriteLine($"{instanceIdentifier}[{parsedKeyExpr}] = {Identifier.element};");
845870
}
@@ -859,19 +884,99 @@ private void EmitBindCoreImplForObject(ObjectSpec type)
859884
string validateMethodCallExpr = $"{Identifier.ValidateConfigurationKeys}(typeof({type.TypeRef.FullyQualifiedName}), {keyCacheFieldName}, {Identifier.configuration}, {Identifier.binderOptions});";
860885
_writer.WriteLine(validateMethodCallExpr);
861886

887+
List<PropertySpec>? initializeBoundProperties = null;
888+
862889
foreach (PropertySpec property in type.Properties!)
863890
{
864-
if (_typeIndex.ShouldBindTo(property))
891+
if (!_typeIndex.ShouldBindTo(property))
865892
{
866-
string containingTypeRef = property.IsStatic ? type.TypeRef.FullyQualifiedName : Identifier.instance;
867-
EmitBindImplForMember(
868-
property,
869-
memberAccessExpr: $"{containingTypeRef}.{property.Name}",
870-
GetSectionPathFromConfigurationExpression(property.ConfigurationKeyName),
871-
canSet: property.CanSet,
872-
canGet: property.CanGet,
873-
InitializationKind.Declaration);
893+
continue;
874894
}
895+
896+
// A property that is populated while the instance is created through its Initialize method - either
897+
// through a matching constructor parameter or as a required/init-only property assigned in the object
898+
// initializer - is already bound at that point. Binding it again here would append to collections
899+
// that Initialize already filled, duplicating their items.
900+
// Defer such properties into a block guarded by !boundThroughConstructor so they are only bound when
901+
// the instance was not created through Initialize (e.g. Bind(existingInstance)), matching the
902+
// reflection binder.
903+
if (IsBoundInInitialize(type, property) && IsPropertyReboundInBindCore(property))
904+
{
905+
(initializeBoundProperties ??= new()).Add(property);
906+
continue;
907+
}
908+
909+
EmitBindImplForProperty(property);
910+
}
911+
912+
if (initializeBoundProperties is not null)
913+
{
914+
EmitStartBlock($"if (!{Identifier.boundThroughConstructor})");
915+
foreach (PropertySpec property in initializeBoundProperties)
916+
{
917+
EmitBindImplForProperty(property);
918+
}
919+
EmitEndBlock();
920+
}
921+
922+
void EmitBindImplForProperty(PropertySpec property)
923+
{
924+
string containingTypeRef = property.IsStatic ? type.TypeRef.FullyQualifiedName : Identifier.instance;
925+
EmitBindImplForMember(
926+
property,
927+
memberAccessExpr: $"{containingTypeRef}.{property.Name}",
928+
GetSectionPathFromConfigurationExpression(property.ConfigurationKeyName),
929+
canSet: property.CanSet,
930+
canGet: property.CanGet,
931+
InitializationKind.Declaration);
932+
}
933+
}
934+
935+
/// <summary>
936+
/// Whether <paramref name="type"/> is an object created through a parameterized constructor that has at
937+
/// least one property bound while the instance is created (through its Initialize method) which would
938+
/// otherwise be re-bound in its <c>BindCore</c> method. Such types receive an extra
939+
/// <c>boundThroughConstructor</c> parameter.
940+
/// </summary>
941+
private bool ShouldEmitBoundThroughConstructorParameter(ComplexTypeSpec type) =>
942+
type is ObjectSpec { Properties: { } properties } objectType &&
943+
properties.Any(property =>
944+
IsBoundInInitialize(objectType, property) &&
945+
_typeIndex.ShouldBindTo(property) &&
946+
IsPropertyReboundInBindCore(property));
947+
948+
/// <summary>
949+
/// Whether <paramref name="property"/> is populated while an instance of <paramref name="type"/> is created
950+
/// through its Initialize method: either it flows through a matching constructor parameter, or it is a
951+
/// required/init-only property assigned in the object initializer. Only parameterized-constructor types have
952+
/// an Initialize method; parameterless-constructor types bind all their properties in <c>BindCore</c>.
953+
/// </summary>
954+
private static bool IsBoundInInitialize(ObjectSpec type, PropertySpec property) =>
955+
type.InstantiationStrategy is ObjectInstantiationStrategy.ParameterizedConstructor &&
956+
(property.MatchingCtorParam is not null || property.SetOnInit);
957+
958+
/// <summary>
959+
/// Whether binding <paramref name="property"/> in a <c>BindCore</c> method emits code that reads from or
960+
/// writes to the property. This mirrors the cases in <see cref="EmitBindImplForMember(MemberSpec, string, string, bool, bool, InitializationKind)"/>
961+
/// that actually emit binding logic; get-only value/string properties, for example, are never re-bound.
962+
/// </summary>
963+
private bool IsPropertyReboundInBindCore(PropertySpec property)
964+
{
965+
switch (_typeIndex.GetEffectiveTypeSpec(property.TypeRef))
966+
{
967+
case ParsableFromStringSpec:
968+
return property.CanGet && property.CanSet;
969+
case ConfigurationSectionSpec:
970+
return property.CanSet;
971+
case ComplexTypeSpec complexType:
972+
// EmitBindImplForMember skips a complex member only when it is a
973+
// parameterized-constructor object with no bindable members. Every other complex member is bound.
974+
return _typeIndex.HasBindableMembers(complexType) ||
975+
complexType.IsValueType ||
976+
complexType is CollectionSpec ||
977+
complexType is not ObjectSpec { InstantiationStrategy: ObjectInstantiationStrategy.ParameterizedConstructor };
978+
default:
979+
return false;
875980
}
876981
}
877982

@@ -881,7 +986,8 @@ private bool EmitBindImplForMember(
881986
string sectionPathExpr,
882987
bool canSet,
883988
bool canGet,
884-
InitializationKind initializationKind)
989+
InitializationKind initializationKind,
990+
bool bindingToLocal = false)
885991
{
886992
string sectionParseExpr = GetSectionFromConfigurationExpression(member.ConfigurationKeyName);
887993

@@ -959,7 +1065,7 @@ private bool EmitBindImplForMember(
9591065
{
9601066
// Early detection of types we cannot bind to and skip it.
9611067
if (!_typeIndex.HasBindableMembers(complexType) &&
962-
!_typeIndex.GetEffectiveTypeSpec(complexType).IsValueType &&
1068+
!complexType.IsValueType &&
9631069
complexType is not CollectionSpec &&
9641070
((ObjectSpec)complexType).InstantiationStrategy == ObjectInstantiationStrategy.ParameterizedConstructor)
9651071
{
@@ -974,7 +1080,7 @@ complexType is not CollectionSpec &&
9741080
string sectionIdentifier = GetIncrementalIdentifier(Identifier.section);
9751081

9761082
EmitStartBlock($"if ({sectionValidationCall} is {Identifier.IConfigurationSection} {sectionIdentifier})");
977-
EmitBindingLogicForComplexMember(member, memberAccessExpr, sectionIdentifier, canSet);
1083+
EmitBindingLogicForComplexMember(member, memberAccessExpr, sectionIdentifier, canSet, bindingToLocal);
9781084
EmitEndBlock();
9791085

9801086
// The current configuration section doesn't have any children, let's check if we are binding to an array and the configuration value is empty string.
@@ -1000,7 +1106,8 @@ private void EmitBindingLogicForComplexMember(
10001106
MemberSpec member,
10011107
string memberAccessExpr,
10021108
string configArgExpr,
1003-
bool canSet)
1109+
bool canSet,
1110+
bool bindingToLocal = false)
10041111
{
10051112

10061113
TypeSpec memberType = _typeIndex.GetTypeSpec(member.TypeRef);
@@ -1061,7 +1168,10 @@ private void EmitBindingLogicForComplexMember(
10611168
_writer.WriteLine($"{tempIdentifierStoringExpr}");
10621169
}
10631170

1064-
if (member.CanGet && _typeIndex.CanInstantiate(effectiveMemberType))
1171+
// When the config section is absent, re-assign the member to itself so any value-mutator
1172+
// setter runs. This is unnecessary when binding into an Initialize local (no accessor to
1173+
// invoke) and would emit a CS1717 self-assignment, so skip it in that case.
1174+
if (!bindingToLocal && member.CanGet && _typeIndex.CanInstantiate(effectiveMemberType))
10651175
{
10661176
EmitEndBlock();
10671177
EmitStartBlock("else");
@@ -1090,7 +1200,8 @@ private void EmitBindingLogic(
10901200
string configArgExpr,
10911201
InitializationKind initKind,
10921202
ValueDefaulting valueDefaulting,
1093-
Action<string, string?>? writeOnSuccess = null)
1203+
Action<string, string?>? writeOnSuccess = null,
1204+
string? constructedExpr = null)
10941205
{
10951206
if (!_typeIndex.HasBindableMembers(type))
10961207
{
@@ -1125,16 +1236,55 @@ private void EmitBindingLogic(
11251236
EmitBindingLogic(memberAccessExpr, initKind);
11261237
}
11271238

1239+
/// <summary>
1240+
/// Emits the instantiation (when required by <paramref name="initKind"/>) and the <c>BindCore</c> call
1241+
/// that binds <paramref name="instanceToBindExpr"/>.
1242+
/// </summary>
1243+
/// <param name="instanceToBindExpr">The local or member expression the value is bound into.</param>
1244+
/// <param name="initKind">How (or whether) <paramref name="instanceToBindExpr"/> is instantiated before binding.</param>
1245+
/// <param name="tempIdentifierStoringExpr">
1246+
/// An optional statement (emitted verbatim after a successful bind) that assigns the just-bound
1247+
/// temporary back into the enclosing binding target - the local the caller is binding into. Value-type
1248+
/// members are bound through a temporary (a value type cannot be bound in place through a property that
1249+
/// returns a copy), so this propagates the bound value back up the temporary chain; the write into the
1250+
/// member itself (which invokes its setter) is emitted separately by the caller's <c>writeOnSuccess</c>.
1251+
/// </param>
11281252
void EmitBindingLogic(string instanceToBindExpr, InitializationKind initKind, string? tempIdentifierStoringExpr = null)
11291253
{
1130-
string bindCoreCall = $@"{nameof(MethodsToGen_CoreBindingHelper.BindCore)}({configArgExpr}, ref {instanceToBindExpr}, defaultValueIfNotFound: {FormatDefaultValueIfNotFound()}, {Identifier.binderOptions});";
1254+
string boundThroughConstructorArg = string.Empty;
11311255

11321256
if (_typeIndex.CanInstantiate(type))
11331257
{
11341258
if (initKind is not InitializationKind.None)
11351259
{
1260+
// The instance is (re)created here. If it goes through a parameterized constructor, tell
1261+
// BindCore not to bind the properties that the constructor already bound. For a null-check
1262+
// assignment the constructor only runs when the existing value was null, so the decision
1263+
// has to be made at run time.
1264+
if (ShouldEmitBoundThroughConstructorParameter(type))
1265+
{
1266+
if (initKind is InitializationKind.AssignmentWithNullCheck)
1267+
{
1268+
string wasNullIdentifier = GetIncrementalIdentifier(Identifier.wasNull);
1269+
_writer.WriteLine($"bool {wasNullIdentifier} = {instanceToBindExpr} is null;");
1270+
boundThroughConstructorArg = $", {Identifier.boundThroughConstructor}: {wasNullIdentifier}";
1271+
}
1272+
else
1273+
{
1274+
boundThroughConstructorArg = $", {Identifier.boundThroughConstructor}: true";
1275+
}
1276+
}
1277+
11361278
EmitObjectInit(type, instanceToBindExpr, initKind, configArgExpr);
11371279
}
1280+
else if (constructedExpr is not null)
1281+
{
1282+
// The caller instantiated the instance separately and provides a run-time flag telling
1283+
// whether it was created through its constructor (e.g. dictionary element binding). The
1284+
// caller only passes it for types that emit the parameter.
1285+
Debug.Assert(ShouldEmitBoundThroughConstructorParameter(type));
1286+
boundThroughConstructorArg = $", {Identifier.boundThroughConstructor}: {constructedExpr}";
1287+
}
11381288

11391289
EmitBindCoreCall();
11401290
}
@@ -1154,6 +1304,7 @@ void EmitBindingLogic(string instanceToBindExpr, InitializationKind initKind, st
11541304

11551305
void EmitBindCoreCall()
11561306
{
1307+
string bindCoreCall = $@"{nameof(MethodsToGen_CoreBindingHelper.BindCore)}({configArgExpr}, ref {instanceToBindExpr}, defaultValueIfNotFound: {FormatDefaultValueIfNotFound()}, {Identifier.binderOptions}{boundThroughConstructorArg});";
11571308
_writer.WriteLine(bindCoreCall);
11581309
writeOnSuccess?.Invoke(instanceToBindExpr, tempIdentifierStoringExpr);
11591310
}

0 commit comments

Comments
 (0)