Skip to content

Developers can get immediate feedback on validation problems #36391

Closed
@HaoK

Description

@HaoK

Updated by @maryamariyan:

Goal

When an application starts, we want to get immediate feedback on validation problems. e.g. we would like to get exceptions thrown on app startup rather than later.

Benefits of eager validation:

  • Enabling this feature forces the program to crash fast when an invalid configuration is passed, as opposed to the default lazy validation only when IOptions<T> is requested

API Proposal

ValidateOnStart feature is implemented as extension to OptionsBuilder<TOptions>
To allow for eager validation, an API suggestion is to add an extension method on OptionsBuilder, (not IHost).

Usage:

services.AddOptions<MyOptions>()
    .ValidateDataAnnotations()
    .ValidateOnStart();                 // Support eager validation

APIs:

According to usage, we'd need the APIs below:

namespace Microsoft.Extensions.DependencyInjection
{
    public static class OptionsBuilderExtensions
    {
        public static OptionsBuilder<TOptions> ValidateOnStart<TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class;
    }
}

Focus of this issue:

The focus here is on eager validation at application startup, and these APIs don't trigger for IOptionsSnapshot and IOptionsMonitor, where values may get recomputed on every request or upon configuration reload after the startup has completed.

  • It would support named options too.
IOptions<TOptions>:
  • Reads configuration data only after the app has started.
  • Does not support named options
IOptionsSnapshot<TOptions>:

May be recomputed on every request, and supports named options

IOptionsMonitor<TOptions>:

Is registered as a singleton, supports named options, change notifications, configuration reloads, and can be injected to any service lifetime.

Original Description (click to view)

AB#1244419
From exp review with @ajcvickers @DamianEdwards @Eilon @davidfowl

We should support some mechanism for eager (fail fast on startup) validation of options.

Needs to also work for generic host as well as webhost, must be configurable on a per options instance, since this will never work for request based options.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bottom Up WorkNot part of a theme, epic, or user storyTeam:LibrariesUser StoryA single user-facing feature. Can be grouped under an epic.api-approvedAPI was approved in API review, it can be implementedarea-Extensions-Options

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions