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?
The problem with your first approach is that with the single-line declaration you have automatically defined the primary constructor, which
In the second case the primary constructor is the parameterless constructor, so it works as expected. Just to clear up any doubts, the
initaccessor is backwards compatible, so even ifConnectionStringis not directly initialized, it takes the valuenull. TheBindmethod will correctly fill it using reflection, I guess.