Skip to content

[API Proposal]: Add a fluent OptionsBuilder method that adds validator types #115200

@89netraM

Description

@89netraM

Background and motivation

Since the introduction of compile-time generated options validators that are NativeAOT compatible, more developers will want to add this kind of validator instead of the reflection-based validators. Adding the reflection-based validator is easy with a fluent OptionsBuilder method, but adding a "user defined" (either implemented by a user or compile-time generated) requires manually adding the validator to the service collection.

I propose a new overload to the Validate method on OptionsBuilder that provides a fluent way of adding validator types for validating an option. Introducing this method would not only make users code more concise but make the way of adding validators more discoverable, since the OptionsBuilder is already the place where most users add validation (often via the ValidateDataAnnotations method).

API Proposal

namespace Microsoft.Extensions.Options;

public class OptionsBuilder<TOptions> where TOptions : class
{
    public virtual OptionsBuilder<TOptions> Validate<TValidateOptions>() where TValidateOptions : class, IValidateOptions<TOptions>;
}

I've made the method virtual because most other methods in OptionsBuilder are. But I don't see the need for it.

API Usage

It would be used in a similar way to how the Validate(Func<TOptions, bool> validation) or ValidateDataAnnotations() for example are used.

services.AddOptions<MyOption>()
    .Validate<MyOptionValidator>();

class MyOption
{
    [Required]
    public required string Config { get; set; }
}

[OptionsValidator]
partial class MyOptionValidator : IValidateOptions<MyOption>;

Alternative Designs

Instead of being an overload to Validate this method could get its own name, like ValidateWithValidator or something similar, which could help with discoverability. (Or the Validate overload might be more discoverable. When looking for this method before realizing it doesn't exist, I looked for a Validate overload, but that's just a sample size of one.)


The same thing can already be achieved with this (slightly more verbose) code snippet, and the new method might not be necessary.

services.AddOptions<MyOption>();
services.AddTransient<IValidateOptions<MyOption>, MyOptionValidator>();

class MyOption
{
    [Required]
    public required string Config { get; set; }
}

[OptionsValidator]
partial class MyOptionValidator : IValidateOptions<MyOption>;

Risks

The only risk I can see is the increased API surface. I cannot imagine any security risks introducing this API since it is syntactical sugar over the already existing way of doing the same thing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions