How can we use non-nullable reference types in combination with the Options pattern?
Let's say we have an options model named MyOptions.
The services requiring those options are getting IOptions<MyOptions> options injected into the constructor.
Configuring the options happens on the IServiceCollection like this:
services
.AddOptions<MyOptions>()
.Configure(options =>
{
options.Name = "ABC";
});
Now, the problem is in the definition of MyOptions:
public sealed class MyOptions
{
public string Name { get; set; }
}
which generates the warning:
CS8618 Non-nullable property 'Name' is uninitialized. Consider declaring the property as nullable.
- We don't want to make
Namenullable as then we need to place traditional null checks everywhere (which is against the purpose of non-nullable reference types) - We can't create a constructor to enforce the
MyOptionsclass to be created with a non-nullablenamevalue as theConfiguremethod construct the options instance for us - We can't use the null-forgiving operator trick (
public string name { get; set; } = null!;) as then we can't ensure theNameproperty is set and we can end up with anullin theNameproperty where this would not be expected (inside the services)
Any other option I forgot to consider?
string.Emptya viable option for your use case? I'm assuming your check for a populated value is to usestring.IsNullOrWhiteSpace. - Jonathon Chase.Validate()call to the options registration method which might serve our needs. Thank you. - huysentruitw