Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
789 views
in Technique[技术] by (71.8m points)

configuration - Bind IConfiguration to C# Record Type

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?

question from:https://stackoverflow.com/questions/65859447/bind-iconfiguration-to-c-sharp-record-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...