runtime: In .Net 7 attempting to Get a configuration section using a type defined as a record will duplicate array values.

Edited by @tarekgh This issue claimed the problem is not occurring on .NET 6.0 which is not true. The comment https://github.com/dotnet/runtime/issues/83803#issuecomment-1480482130 clarified that. In short, this issue is not a regression from .NET 6.0. Actually, .NET 7.0 behavior is not throwing. End of @tarekgh edit

This issue has been moved from a ticket on Developer Community.


[severity:It bothers me. A fix would be nice] The behaviour has changed unexpectedly from how .Net 6.0 used to work.

/* Environment Variables
"MonitorConfig__Services__0__Name": "Service A"
"MonitorConfig__Services__0__Url": "http://localhost:5201/health",
"MonitorConfig__Services__1__Name": "Service B",
"MonitorConfig__Services__1__Url": "http://localhost:5202/health"
*/

/* defined Records types
public record MonitorConfig(ServiceConfig[] Services = null);

public record ServiceConfig(string Name, string Url);
*/

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddEnvironmentVariables();

var monitorConfig = builder.Configuration.GetSection("MonitorConfig").Get();

monitorConfig will contain 4 ServiceConfig entries with duplicated instances of both ServiceA and ServceB declarations.

The expectation should be two entries as defined by the environment variables.

If I convert to use class types instead of record types, the behaviour works as expected.

The use of records should be supported and work as it did for .Net 6.0 using the same code, as I should not have to go and rewrite records to as classes after porting to .Net 7.


Original Comments

Feedback Bot on 3/8/2023, 05:37 PM:

(private comment, text removed)


Original Solutions

Chris Westermann solved on 3/9/2023, 05:05 AM, 0 votes:

I found that if I override the default constructor, then I get the behaviour I would expect

public record MonitorConfig(ServiceConfig[] Services)
{
public MonitorConfig()
: this((ServiceConfig[])null)
{ }
}

While this is a workaround, it seems odd I would need to do this since, conceptually, setting the default value of the positional parameter to null should produce the same behaviour and not cause the actual instance to have twice as many array entries as expected.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 16 (6 by maintainers)

Most upvoted comments

Edit: I actually found a workaround that makes the List itself private and exposes a ReadOnly version as a property.

@Blackclaws can you share the workaround? I’m curious about how it works. Wouldn’t the second call fail when trying to add elements to the ReadOnly list?

It doesn’t try to add elements because it is read only.

public record TestClass {
    public TestClass(List<ComplexClass> portConfig) =>
            _portConfig = portConfig;

    private List<ComplexClass>          _portConfig { get; } = new();
    public  IReadOnlyList<ComplexClass> PortConfig  => _portConfig.AsReadOnly();
}

Just for other people who may face this issue, we ended up with a “workaround”. Instead of using arrays or lists, we use HashSet. The problem is still there (HashSet is initialized in the constructor and then the add method is called) but given the HashSet won’t allow duplicate entries, it “fixes” the problem.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration; 
// requires package Microsoft.Extensions.Configuration.Binder

internal class Program
{
    private static void Main(string[] args)
    {
        var json = """
            {
                "MyConfig" : {
                    "values": ["v1", "v2"]
                }
            }
            """;

        var configuration = new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(json))).Build();

        var myConfigSection = configuration.GetSection("MyConfig");
        var arrayConfig = myConfigSection.Get<ArrayConfig>();
        var listConfig = myConfigSection.Get<ListConfig>();
        var hashSetConfig = myConfigSection.Get<HashSetConfig>();

        Console.WriteLine("Array entries: "+ string.Join(", ", arrayConfig?.Values));
        Console.WriteLine("List entries: " + string.Join(", ", listConfig?.Values));
        Console.WriteLine("HashSet entries: " + string.Join(", ", hashSetConfig?.Values));


    }
}

public record ArrayConfig(string[] Values);
public record ListConfig(List<string> Values);
public record HashSetConfig(HashSet<string> Values);

Output

Array entries: v1, v2, v1, v2
List entries: v1, v2, v1, v2
HashSet entries: v1, v2

I largely concur with your assessment in this matter. Our current challenge revolves around resolving the binding issue with the record. As you rightly pointed out, tackling this issue to prevent the binding of properties twice should also effectively address the scenario you’ve outlined.

I appreciate there may be cases where the example provided in Binding config to dictionary extends values makes sense

The example is streamlined to illustrate the behavior. In some cases, users create an object and bind it to multiple configuration sources, anticipating the aggregation of values from various configurations. I share your agreement that utilizing a record is not the intended scenario, and this is something we need to address by preventing the occurrence of double binding.

Without the workaround of adding a default public constructor, this code actually throws an exception in .NET 6.0 - but the original posted said it used to work. Here is the behaviors based on my experimentation:

Runtime Has default public constructor Behavior
.NET 6.0 Yes Runs - creates two ServiceConfig elements
.NET 7.0 Yes Runs - creates two ServicConfig elements
.NET 6.0 No Runtime exception about lack of public constructor
.NET 7.0 No Runs - creates four ServiceConfig elements

It looks like logic was added in .NET 7.0 to support non-default constructors where the parameters line up with properties (basically record types). But it’s possible that there is a bug in there somewhere.