How to validate configuration settings using IValidateOptions in ASP.NET Core 2.2?

前端 未结 4 2171
[愿得一人]
[愿得一人] 2021-02-14 15:57

Microsoft\'s ASP.NET Core documentation briefly mentions that you can implement IValidateOptions to validate configuration settings from appsettings

4条回答
  •  长发绾君心
    2021-02-14 16:33

    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)options).Value;
                }
    
                next(builder);
            };
        }
    }
    
    
    

    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();
    

    提交回复
    热议问题