Skip to content

Microsoft.Extensions.Configuration.Binder: Fix complex types in constructors - #74981

Merged
maryamariyan merged 1 commit into
dotnet:mainfrom
Saalvage:configurationbinder/fix-complex-types-in-ctor
Sep 9, 2022
Merged

maryamariyan merged 1 commit into
dotnet:mainfrom
Saalvage:configurationbinder/fix-complex-types-in-ctor

Conversation

@Saalvage

@Saalvage Saalvage commented Sep 2, 2022 •

Copy link
Copy Markdown
Contributor

Currently, the following code:

var dic = new Dictionary<string, string>
{
    {"BaseInt", "42"},
    {"Nested:String", "ABC"},
    {"Nested:Int", "1"},
};

var test = new ConfigurationBuilder()
    .AddInMemoryCollection(dic)
    .Build()
    .Get<Test>();

Console.WriteLine(test.ToString());

record Nested(string String, int Int);
record Test(int BaseInt, Nested Nested);

produces:
System.InvalidOperationException: 'Cannot create instance of type 'Test' because parameter 'Nested' has no matching config. Each parameter in the constructor that does not have a default value must have a corresponding config entry.'

However, when giving the Nested property a default value of null! everything works as expected, including the correct values being printed, suggesting a bug.

The issue is caused by BindParameter prematurely cancelling the binding operator when neither GetSection nor a possible default assignment manage to produce a value. This ignores the possibility of a parameter first acquiring a value via the BindInstance call, as is the case - e.g. - with basic record types (among many others).

An unintended side effect is that BindInstance will no longer be called after the value has been provided by a defaulted parameter. However, since in that case the types have to match anyways I think the call was previously redundant in that case anyways.

Parameters of types which first acquire their value via instance binding (such as simple record types) were not being given the chance to bind before throwing a config missing error erroneously
@ghost ghost added area-Extensions-Configuration community-contribution Indicates that the PR has been added by a community member labels Sep 2, 2022
@dnfadmin

dnfadmin commented Sep 2, 2022 •

Copy link
Copy Markdown

CLA assistant check
All CLA requirements met.

@ghost

ghost commented Sep 2, 2022

Copy link
Copy Markdown

Tagging subscribers to this area: @dotnet/area-extensions-configuration
See info in area-owners.md if you want to be subscribed.

Issue Details

Currently, the following code:

var dic = new Dictionary<string, string>
{
    {"BaseInt", "42"},
    {"Nested:String", "ABC"},
    {"Nested:Int", "1"},
};

var test = new ConfigurationBuilder()
	.AddInMemoryCollection(dic)
    .Build()
    .Get<Test>();

Console.WriteLine(test.ToString());

record Nested(string String, int Int);
record Test(int BaseInt, Nested Nested);

produces:
*System.InvalidOperationException: 'Cannot create instance of type 'Test' because parameter 'Nested' has no matching config. Each parameter in the constructor that does not have a default value must have a corresponding config entry.'

However, when giving the Nested property a default value of null! everything works as expected, including the correct values being printed, suggesting a bug.

The issue is caused by BindParameter prematurely cancelling the binding operator when neither GetSection nor a possible default assignment manage to produce a value. This ignores the possibility of a parameter first acquiring a value via the BindInstance call, as is the case - e.g. - with basic record types (among many others).

An unintended side effect is that BindInstance will no longer be called after the value has been provided by a defaulted parameter. However, since in that case the types have to match anyways I think the call was previously redundant in that case anyways.

Author: Saalvage
Assignees: -
Labels:

area-Extensions-Configuration

Milestone: -


var propertyBindingPoint = new BindingPoint(initialValue: config.GetSection(parameterName).Value, isReadOnly: false);

BindInstance(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@halter73 @eerhardt the change looks reasonable to me. The only thing I am seeing is it is possible BindInstance throws exceptions which users may start getting when used to get InvalidOperationException before. I am not sure if this is be a concern or would be acceptable.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems fine. Test ExceptionWhenTryingToBindToConstructorWithMissingConfig covers the exception case

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tarekgh - do you have specific exception scenarios in mind? I'm not seeing any.

The only thing I can think of that this may break is default values on the ctor parameter. We should have a test for it, if we don't we should add one.

@tarekgh tarekgh Sep 7, 2022 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The scenario in my head is before the change we used to throw throw new InvalidOperationException(SR.Format(SR.Error_ParameterHasNoMatchingConfig, type, parameterName));. Now with the change, we call BindInstance first which is possible to throw a different exception (like when calling TryConvertValue). So, it is possible the users will get different exceptions. I am not sure if this is a real concern though.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking more, I am seeing we always throw InvalidOperationException. So, i think we fine then. You can ignore this comment.

@eerhardt eerhardt left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change looks good to me, as long as we ensure we have a test for default valued parameters in a record constructor.

@maryamariyan

Copy link
Copy Markdown
Contributor

This change looks good to me, as long as we ensure we have a test for default valued parameters in a record constructor.

@Saalvage can you add a test for this case?

@Saalvage

Saalvage commented Sep 8, 2022

Copy link
Copy Markdown
Contributor Author

@maryamariyan Does the existing test here not fit the bill?

public record RecordWhereParametersHaveDefaultValue(string Name, string Address, int Age = 42);

[Fact]
public void BindsToRecordPrimaryConstructorParametersWithDefaultValues()
{
var input = new Dictionary<string, string>
{
{"RecordWhereParametersHaveDefaultValueProperty:Name", "John"},
{"RecordWhereParametersHaveDefaultValueProperty:Address", "123, Abc St."}
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(input);
var config = configurationBuilder.Build();
TestOptions testOptions = new TestOptions();
config.Bind(testOptions);
Assert.Equal("John", testOptions.RecordWhereParametersHaveDefaultValueProperty.Name);
Assert.Equal("123, Abc St.", testOptions.RecordWhereParametersHaveDefaultValueProperty.Address);
Assert.Equal(42, testOptions.RecordWhereParametersHaveDefaultValueProperty.Age);
}

@maryamariyan
maryamariyan merged commit ca0d3e4 into dotnet:main Sep 9, 2022
@maryamariyan

Copy link
Copy Markdown
Contributor

I was thinking of another one with default record that would throw too. Consulted with @eerhardt and he believes this one is sufficient, so merging.

@Saalvage
Saalvage deleted the configurationbinder/fix-complex-types-in-ctor branch September 9, 2022 18:27
@ghost ghost locked as resolved and limited conversation to collaborators Oct 9, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-Extensions-Configuration community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants