Skip to content

Configuration binder failed when getter of read only property throw exception #65710

Closed

Description

@lenraven

Description

The problem

When I try to add a read only property, what based on my configuration, the Binding of configuration will throw the following exception.

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.ArgumentNullException: Value cannot be null. (Parameter 'source')
   at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
   at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
   at BindPropertyExceptionSample.Configuration.get_FilteredConfigValues() in C:\Source\Github\BindPropertyExceptionSample\BindPropertyExceptionSample\Configuration.cs:line 5
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.PropertyInfo.GetValue(Object obj)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindProperty(PropertyInfo property, Object instance, IConfiguration config, BinderOptions options)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindNonScalar(IConfiguration configuration, Object instance, BinderOptions options)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config, BinderOptions options)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration configuration, Object instance, Action`1 configureOptions)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration configuration, Object instance)
   at Program.<Main>$(String[] args) in C:\Source\Github\BindPropertyExceptionSample\BindPropertyExceptionSample\Program.cs:line 12

Sample

Configuration.cs

public class Configuration
{
    public IEnumerable<int> FilteredConfigValues => ConfigValues.Where(p => p > 10);
    public IEnumerable<int> ConfigValues { get; set; } = null!;
}

appsettings.json:

{
    "Logging": {
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "TestConfig": {
        "ConfigValues": [ 1, 10, 100, 1000 ]
    }
}

Program.cs

using BindPropertyExceptionSample;

using Microsoft.Extensions.Configuration;

var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .Build();

var testConfig = new Configuration();
config.GetSection("TestConfig").Bind(testConfig); // The exeption will be thrown here.

Console.WriteLine($"Filtered config values: {string.Join(", ", testConfig.FilteredConfigValues)}");

Reason

The ConfigurationBinder.BindProperty is reading the value of the property before it decide is there setter of property.
At this line: object? propertyValue = property.GetValue(instance);

Reproduction Steps

You can find a repository with a sample code of the issue here.

Expected behavior

Skip the read only properties during the binding.

Actual behavior

An exception was thrown when I call the Bind of configuration.

Regression?

No response

Known Workarounds

No response

Configuration

Target framework: NET 6.0
SDK: 6.0.101
Operating system: Windows 10
Architecture x64

Other information

No response

Activity

  1. ghost added
    untriaged
    on Feb 22, 2022
  2. added
    help wanted
    and removed
    untriaged
    on Mar 15, 2022
  3. added this to the Future milestone on Mar 15, 2022
  4. madelson commented on Mar 16, 2022

    @madelson
    Contributor

    Possible duplicate of #52905

  5. added a commit that references this issue on Mar 16, 2022
    99f977b
  6. ghost added
    in-pr
    on Mar 16, 2022
  7. maryamariyan commented on Mar 25, 2022

    @maryamariyan
    Contributor

    Thanks for the report. Just noticed that this NRE stacktrace is pointing to the where clause below in the user code itself, during the Bind call:

    public class Configuration
    {
        public IEnumerable<int> FilteredConfigValues => ConfigValues.Where(p => p > 10);
        public IEnumerable<int> ConfigValues { get; set; } = null!;
    }
    System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
     ---> System.ArgumentNullException: Value cannot be null. (Parameter 'source')
       at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
       at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
       at BindPropertyExceptionSample.Configuration.get_FilteredConfigValues() in C:\Source\Github\BindPropertyExceptionSample\BindPropertyExceptionSample\Configuration.cs:line 5
       --- End of inner exception stack trace ---
    

    This looks like a very corner case bug.

    It had been reported earlier too and we reverted its fix since it caused a regression.
    Link to the PR reverting original fix: #63586
    Let's make sure to add a test case for the regression scenario that was reported in #63479

  8. tarekgh commented on Mar 25, 2022

    @tarekgh
    Member

    Just to note, if flipping the order of the properties, this should workaround this issue:

    public class Configuration
    {
        public IEnumerable<int> ConfigValues { get; set; } = null!;
        public IEnumerable<int> FilteredConfigValues => ConfigValues.Where(p => p > 10);
    }
  9. ghost removed
    in-pr
    on Apr 2, 2022
  10. ghost locked as resolved and limited conversation to collaborators on May 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Extensions-Configurationhelp wanted

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions