Microsoft\'s ASP.NET Core documentation briefly mentions that you can implement IValidateOptions
to validate configuration settings from appsettings
Probably too late now, but for the benefit of anyone else that stumbles across this...
Near the bottom of the documentation section (linked to in the question), this line appears
Eager validation (fail fast at startup) is under consideration for a future release.
On searching a little more for information on this, I came across this github issue, which provides an IStartupFilter, and an extension method for IOptions (which I've repeated below just incase the issue disappears)...
This solution ensures that the options are validated ahead of the application "running".
public static class EagerValidationExtensions {
public static OptionsBuilder ValidateEagerly(this OptionsBuilder optionsBuilder)
where TOptions : class, new()
{
optionsBuilder.Services.AddTransient>();
return optionsBuilder;
}
}
public class StartupOptionsValidation: IStartupFilter
{
public Action Configure(Action next)
{
return builder =>
{
var options = builder.ApplicationServices.GetRequiredService(typeof(IOptions<>).MakeGenericType(typeof(T)));
if (options != null)
{
var optionsValue = ((IOptions
I then have, an extension method called from within ConfigureServices that looks like this
services
.AddOptions()
.Configure(options=>{ options.SomeProperty = "abcd" })
.Validate(x=>
{
// do FluentValidation here
})
.ValidateEagerly();