Bind IConfiguration to C# Record Type

Viewed 1565

I would like to bind configuration to record type.

This is definition of configuration type (it is without parameterless constructor):

public record AppConfiguration(string ConnectionString);

This is sample Main method:

public static void Main(string[] args)
{
    var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    AppConfiguration appConfig = new(); // error
    configuration.GetSection("app").Bind(appConfig);
}

If I convert definition to this:

public record AppConfiguration
{
    public string ConnectionString {get; init;}
}

it works as expected, but I would rather use "single line" definition of the record. Are records right way for this use case?

3 Answers

The problem with your first approach is that with the single-line declaration you have automatically defined the primary constructor, which

causes the implicitly declared default class constructor, if present, to be suppressed.

In the second case the primary constructor is the parameterless constructor, so it works as expected. Just to clear up any doubts, the init accessor is backwards compatible, so even if ConnectionString is not directly initialized, it takes the value null. The Bind method will correctly fill it using reflection, I guess.

I have created a tiny NuGet package to handle binding config to positional records or classes without parameterless constructors.

If you reference the package then you just need a single line:

configuration.Bind<AppConfiguration>();

If your config file section doesn't match the type name then you can pass the section name:

configuration.Bind<AppConfiguration>("app");
Related