skip to content

In ASP.NET Core, when would you write an IValidateOptions<T> class or use the [OptionsValidator] source generator instead of ValidateDataAnnotations?

level: seniorimportance: should knowfreq 30%

answer

  1. rules across several properties
  2. Validate(name, options) returns ValidateOptionsResult
  3. Success, Fail, Skip
  4. empty partial class, generated at compile time
  5. register as IValidateOptions<T> singleton

basics

~20 s

Write an IValidateOptions<T> when a rule spans properties or needs logic attributes cannot express; use an [OptionsValidator] partial class when you want the DataAnnotations rules checked by compile-time generated code, without reflection, for trimmed or Native AOT apps.

solid answer

~30 s

`IValidateOptions<T>` has one method, `Validate(string? name, T options)`, returning `ValidateOptionsResult.Success`, `ValidateOptionsResult.Fail(...)` or `ValidateOptionsResult.Skip`. A class gives you room for cross-property rules (a mail relay that needs credentials only when `UseStartTls` is false), named-instance checks and multiple messages, and it can take constructor dependencies. Register it with `TryAddEnumerable(ServiceDescriptor.Singleton<IValidateOptions<MailOptions>, MailOptionsValidator>())` or `AddOptionsWithValidateOnStart<MailOptions, MailOptionsValidator>()`. The `[OptionsValidator]` attribute on an empty `partial` class that implements `IValidateOptions<T>` makes a source generator write the validation code for the DataAnnotations attributes at compile time; you register it the same way and skip `ValidateDataAnnotations()`. Both run in the options factory, so `ValidateOnStart()` still decides when.

code

csharp · 16 lines
csharp
public sealed class PaymentGatewayOptions
{
    [Required, Url] public string BaseUrl { get; set; } = "";
    [Required] public string ApiKey { get; set; } = "";
    [Range(1, 120)] public int TimeoutSeconds { get; set; } = 30;
}

[OptionsValidator]
public partial class PaymentGatewayOptionsValidator
    : IValidateOptions<PaymentGatewayOptions>
{
}

builder.Services.AddOptionsWithValidateOnStart<PaymentGatewayOptions,
        PaymentGatewayOptionsValidator>()
    .BindConfiguration("PaymentGateway");

go deeper

for a junior

Know that options can have custom validation beyond attributes, written as a class that implements IValidateOptions<T>.

for a middle

Explain the Validate(name, options) signature, the Success, Fail and Skip results, and how to register a validator.

for a senior

Use classes for cross-property and per-name rules, switch DataAnnotations to [OptionsValidator] for trimmed or AOT builds, and avoid double registration.

for a principal

Decide where configuration rules live, attributes versus validator classes, so they stay testable and consistent across services.

## What a validator is Every options validator implements one interface: ```csharp public interface IValidateOptions<TOptions> where TOptions : class { ValidateOptionsResult Validate(string? name, TOptions options); } ``` `ValidateDataAnnotations()` and `Validate(lambda)` are just registrations of built-in implementations. When the options factory builds an instance, it calls every registered `IValidateOptions<T>` and collects the failures into one `OptionsValidationException`. The result type has three shapes: - `ValidateOptionsResult.Success` - the instance is valid. - `ValidateOptionsResult.Fail(message)` or `Fail(IEnumerable<string>)` - invalid, with messages. - `ValidateOptionsResult.Skip` - this validator does not apply, typically because `name` is a named instance it does not own. ## When a class beats attributes | Need | Attributes | `IValidateOptions<T>` class | |---|---|---| | One property, simple rule | Yes | Overkill | | Rule across properties | Awkward (`IValidatableObject`) | Natural | | Different rules per named instance | No | Check `name` | | Needs a service (clock, lookup) | No | Constructor injection | | Several messages per rule | One per attribute | Any number | ```csharp public sealed class MailOptionsValidator : IValidateOptions<MailOptions> { public ValidateOptionsResult Validate(string? name, MailOptions o) { var failures = new List<string>(); if (o.Port is 25 && o.UseStartTls) failures.Add("Port 25 with STARTTLS is not allowed for the order mailer."); if (!o.UseStartTls && string.IsNullOrEmpty(o.RelayUser)) failures.Add("RelayUser is required when STARTTLS is off."); return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures); } } builder.Services.AddOptionsWithValidateOnStart<MailOptions, MailOptionsValidator>() .BindConfiguration("Mail"); ``` `AddOptionsWithValidateOnStart<TOptions, TValidateOptions>()` registers the validator as a singleton through `TryAddEnumerable` and applies `ValidateOnStart()`. Because the validator is a singleton, it should depend only on singletons. ## The [OptionsValidator] source generator `ValidateDataAnnotations()` discovers attributes by reflection at run time. That costs time on each validation and produces trimming warnings, which matter for trimmed and Native AOT publishing. The options library also ships a source generator that does the same job at compile time: ```csharp [OptionsValidator] public partial class PaymentGatewayOptionsValidator : IValidateOptions<PaymentGatewayOptions> { } builder.Services.AddSingleton<IValidateOptions<PaymentGatewayOptions>, PaymentGatewayOptionsValidator>(); ``` The generator reads the DataAnnotations attributes on `PaymentGatewayOptions` and fills in `Validate` in a generated file. Three rules to remember: 1. The class must be `partial` and declare `IValidateOptions<T>`; the attribute alone does nothing. 2. Do **not** also call `ValidateDataAnnotations()`, or every rule runs twice and messages repeat. 3. Nested classes still need `[ValidateObjectMembers]` and collections `[ValidateEnumeratedItems]`; the generator follows the same opt-in. ## Testing a validator A validator is a plain class, so it tests without a host: ```csharp var result = new MailOptionsValidator().Validate(Options.DefaultName, new MailOptions { Port = 25, UseStartTls = true }); Assert.True(result.Failed); ``` `ValidateOptionsResult` exposes `Succeeded`, `Skipped`, `Failed`, `Failures` and a joined `FailureMessage`, which is enough to assert on each rule separately. ## Named instances A validator registered for a type sees every instance of that type, named or not. A validator meant for one name returns `Skip` for the others: ```csharp if (name != "Marketing") return ValidateOptionsResult.Skip; ``` ## Interview checklist - `Validate(name, options)` returning `Success`, `Fail` or `Skip`. - Classes for cross-property, per-name or dependency-backed rules. - `[OptionsValidator]` on an empty partial class for reflection-free DataAnnotations. - Register as `IValidateOptions<T>`; `ValidateOnStart()` still decides timing.

  • Why should an [OptionsValidator] setup not also call ValidateDataAnnotations()?
    Both register an `IValidateOptions<T>` that checks the same attributes: one generated at compile time, one using reflection. The factory runs every registered validator, so each rule runs twice and every failure message appears twice; keep only the generated validator.
  • Can an IValidateOptions<T> class use other services?
    Yes, through its constructor, since the container creates it. `AddOptionsWithValidateOnStart` registers it as a singleton and singleton options services consume it, so it should depend only on singletons such as `TimeProvider`; a scoped dependency would be captured for the app's lifetime.

  • Adding [OptionsValidator] to the options class itself is enough to validate it.
  • A custom IValidateOptions<T> replaces the need for ValidateOnStart.
  • ValidateOptionsResult.Skip means the instance passed validation.
  • The source-generated validator must be combined with ValidateDataAnnotations to run.
  • IValidateOptions<T> validators run only for the default unnamed instance.