Skip to content

Allow configuration binding to set-only properties #63508

@ogxd

Description

@ogxd

Currently, according to the documentation, with the binding option BindNonPublicProperties the binder will attempt to set all non-read-only properties.
However, this is not true for set-only properties (it's not a read-only property).

I took a look at the code to see why this does not work, and it seems this is intentional:

// We don't support set only, non public, or indexer properties
if (property.GetMethod == null ||
    (!options.BindNonPublicProperties && !property.GetMethod.IsPublic) ||
    property.GetMethod.GetParameters().Length > 0)
{
    return;
}

I am not sure why this is so because by removing the null check it still works, tests are passing and it is now closer to the behavior documentation describes.

Removing this allows nice things such as leveraging set-only properties for custom types in configuration, built from primitive types supported by the binder.
Here is one example with TimeSpan, a type very commonly used in configurations:

public class MyConfiguration
{
    public double TimeoutSeconds { set => Interval = TimeSpan.FromSeconds(value); }
    public TimeSpan Timeout { get; private set; }
}

With this example, we can use "TimeoutSeconds" for configuration keys with integer values while having a TimeSpan in the code and a setter for the tests.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions