Skip to content

Binding to non-null IEnumerable doesn't work #36390

Closed
@brockallen

Description

@brockallen

AB#1277574
When using the binding feature in the config system, for IEnumerable collections that have a default, non-null value, the collection is never assigned into the target model. For example:

For this json:

{
  "config": {
    "data": [ "a", "b" ]
  }
}

and this application code:

 public class Config
    {
        IEnumerable<string> _data = new List<string>();
        public IEnumerable<string> Data
        {
            get
            {
                return _data;
            }
            set
            {
                _data = value;
            }
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("test.json")
                .Build();

            var val = config.GetSection("config").Get<Config>();
            Console.WriteLine(val?.Data?.Count());
        }
    }

The output is:

0
Press any key to continue . . .

I'd expect it to print "2".

I'd argue the issue is in BindInstance and explicit handling for IEnumerable should be made (much like the check for IsArray https://github.com/aspnet/Configuration/blob/dev/src/Microsoft.Extensions.Configuration.Binder/ConfigurationBinder.cs#L281).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions