Today the IOptions<TOptions> pattern is built around the mutability of the TOptions until first use (though nothing prevents later mutation). We should investigate what it would mean to consume immutable TOptions in the options system. Today, the system constructs TOptions using Activator.CreateInstance then executes a series of delegates on top of that instead to produce the "final" instance (see
|
public TOptions Create(string name) |
)
An alternative model would be to do the same thing but execute delegates that return a new instance of the options object instead of mutating the current instance. We would need to figure out how to support both side by side but it would allow designing immutable options objects.
Here's an example of what we what it would look like:
public record MyImmutableOption(string Name, int Size);
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyImmutableOption>(o =>
{
return o with { Name = "Foo" };
});
}
cc @ericstj @eerhardt @maryamariyan
Today the
IOptions<TOptions>pattern is built around the mutability of theTOptionsuntil first use (though nothing prevents later mutation). We should investigate what it would mean to consume immutableTOptionsin the options system. Today, the system constructsTOptionsusingActivator.CreateInstancethen executes a series of delegates on top of that instead to produce the "final" instance (seeruntime/src/libraries/Microsoft.Extensions.Options/src/OptionsFactory.cs
Line 46 in 546115d
An alternative model would be to do the same thing but execute delegates that return a new instance of the options object instead of mutating the current instance. We would need to figure out how to support both side by side but it would allow designing immutable options objects.
Here's an example of what we what it would look like:
cc @ericstj @eerhardt @maryamariyan