Can I use C# 9 records as IOptions?

Is there any way to configure the IOptions configuration system to deserialize the options using the record’s constructor instead of requiring a parameterless constructor?

No, in general ASP.Net Core uses a lot of run-time type instancing, which requires constructor calls that are known beforehand, and in this case it requires a constructor with no arguments.

You can however make your record class have a parameter-less constructor:

public record MyOptions(string OptionA, int OptionB)
{
    public MyOptions(): this(default, default) {}
}

Is it worth it? Eh. Up to you. It’s no worse than a regular class, performance-wise, so go with whatever you find clearer!

Edit: alternatively, you should be able to use this form:

public record MyOptions(string OptionA = default, int OptionB = default);

Leave a Comment