dotnet/runtime

Support immutable types with configuration binding

davidfowl opened this issue ยท 17 comments

Similar to #43359 but specifically for configuration binding. Support binding from IConfiguration to say a record or any immutable .NET object. This has been solved in JSON (it's basically deserialization) and we can use any lessons learned there to implement a solution in configuration.

public record Settings(string Color, int Length);

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<Settings>(Configuration.GetSection("MySettings"));
}

Tagging subscribers to this area: @maryamariyan
See info in area-owners.md if you want to be subscribed.

Tagging subscribers to this area: @maryamariyan
See info in area-owners.md if you want to be subscribed.

Tagging subscribers to this area: @maryamariyan
See info in area-owners.md if you want to be subscribed.

6.0 is now feature complete. Moving to 7.0.

Disappointing that this was not implemented in 6.0 to be honest.

@maryamariyan - I'm happy to look at this one

@maryamariyan - I'm happy to look at this one

@SteveDunn sure looking forward to it

Hi @davidfowl - I've created a PR for this. I had a question:

Currently, a ConfigurationKeyNameAttribute can be applied to properties. Do we want this to also now be applicable to parameters?

Also, my implementation picks the biggest non-parameterless constructor and binds as many parameters as it can. I don't know how smart we need to be for this, but this seems like a reasonable starting point.

Will this change also make it so that configuration can now be bound to a class that has a non-empty constructor? ๐Ÿ™‚

e.g.

public class User
{
    public string Username { get; }
    public string Password { get; }

    public User(string username, string password)
    {
        Username = username ?? ArgumentNullException.ThrowIfNull(username);
        Password = password ?? ArgumentNullExeption.ThrowIfNull(password);
    }
}

Yes, @Bosch-Eli-Black - that, and records with primary constructors

@davidfowl - you mentioned JSON in this description, so in the PR, we've borrowed some ideas from S.T.J. What are your thoughts on this thread in the PR?

Yes, @Bosch-Eli-Black - that, and records with primary constructors

@SteveDunn Great, thanks! ๐Ÿ™‚

So very pleased to see this feature done. It'll be useful to a lot of people. And it's been great to be able to contribute to a library that's used by so many people. Big thanks to the reviewers for steering such a feature to completion.

SteveHarveyHappyGIF

So we can expect this feature to be shipped in .NET 7? ๐Ÿ˜Š

Yes

Thanks a ton for the implementation, @SteveDunn ! ๐Ÿ™‚