The bypass architecture creates a decoupled registration model: ValidateDataAnnotationsAsync() registers IAsyncValidateOptions<T> validators, but those validators are only consumed when ValidateOnStartAsync() registers an IAsyncStartupValidator. If the developer calls one without the other, async validation is silently skipped with zero warnings, zero errors, and zero protection.
Four Misuse Patterns
Pattern 1: Forgot ValidateOnStartAsync()
─────────────────────────────────────────
.ValidateDataAnnotationsAsync() ← registers IAsyncValidateOptions<T>
// no .ValidateOnStartAsync() ← nothing consumes it
// Result: [AsyncFoo] attrs are SILENTLY IGNORED
Pattern 2: Used ValidateOnStart() instead of ValidateOnStartAsync()
───────────────────────────────────────────────────────────────────
.ValidateDataAnnotationsAsync() ← registers IAsyncValidateOptions<T>
.ValidateOnStart() ← only triggers SYNC validators
// Result: [AsyncFoo] attrs are SILENTLY IGNORED
Pattern 3: Lambda ValidateAsync() without startup trigger
─────────────────────────────────────────────────────────
.ValidateAsync(async (opts, ct) => ..., "msg") ← registers IAsyncValidateOptions<T>
// no .ValidateOnStartAsync()
// Result: lambda NEVER RUNS
Pattern 4: Non-hosted scenario (Console app without Generic Host)
────────────────────────────────────────────────────────────────
var services = new ServiceCollection();
services.AddOptions<MyOpts>()
.ValidateDataAnnotationsAsync()
.ValidateOnStartAsync(); ← registers IAsyncStartupValidator
var sp = services.BuildServiceProvider();
var opts = sp.GetRequiredService<IOptions<MyOpts>>();
opts.Value; ← sync access, nobody called IAsyncStartupValidator.ValidateAsync()
// Result: startup validator exists but was never invoked
Per the gap analysis comparison matrix, Gap 1 (no host / no startup trigger) is the only gap that produces zero validation with zero warning. All other gaps produce partial validation, timing issues, or are explicitly opt-in. This is the difference between "works incorrectly" and "appears to work but doesn't."
The team consensus is that sync APIs encountering async validators should throw, not silently degrade. Errors should signal developer misuse, not be user-facing validation errors. An InvalidOperationException is the appropriate enforcement mechanism.
Concept: Register a sync IValidateOptions<T> implementation as a sentinel. When the sync pipeline runs (via OptionsFactory.Create() → .Value access), the guard checks whether an IAsyncStartupValidator is registered and has been invoked. If not, it throws.
internal sealed class AsyncValidationGuard<TOptions> : IValidateOptions<TOptions>
where TOptions : class
{
private readonly bool _hasAsyncStartupValidator;
public AsyncValidationGuard(IServiceProvider serviceProvider)
{
_hasAsyncStartupValidator =
serviceProvider.GetService<IAsyncStartupValidator>() is not null;
}
public ValidateOptionsResult Validate(string? name, TOptions options)
{
if (!_hasAsyncStartupValidator)
{
throw new InvalidOperationException(
$"Async validation attributes are registered for " +
$"'{typeof(TOptions).Name}' (via ValidateDataAnnotationsAsync() " +
$"or ValidateAsync()), but ValidateOnStartAsync() was not called. " +
$"Async validators only run during Host.StartAsync(). " +
$"Add .ValidateOnStartAsync() to your options configuration, or " +
$"use ValidateDataAnnotations() for sync-only validation.");
}
return ValidateOptionsResult.Success;
}
}Registration: ValidateDataAnnotationsAsync() and each ValidateAsync() overload add the guard via TryAddSingleton:
optionsBuilder.Services.TryAddSingleton<IValidateOptions<TOptions>>(
sp => new AsyncValidationGuard<TOptions>(sp));Flow:
.ValidateDataAnnotationsAsync() registers BOTH:
├── IAsyncValidateOptions<T> (DataAnnotationValidateOptionsAsync)
└── IValidateOptions<T> (AsyncValidationGuard)
Case 1: NO .ValidateOnStartAsync() First .Value access:
└── OptionsFactory.Create()
└── foreach IValidateOptions<T>:
└── AsyncValidationGuard.Validate()
└── IAsyncStartupValidator not in DI
→ throw InvalidOperationException ✅
Case 2: WITH .ValidateOnStartAsync() Host.StartAsync():
├── IAsyncStartupValidator.ValidateAsync()
│ └── runs all IAsyncValidateOptions<T> ✅
└── First .Value access:
└── OptionsFactory.Create()
└── AsyncValidationGuard.Validate()
└── IAsyncStartupValidator IS in DI
→ ValidateOptionsResult.Success ✅
Pros:
- ~40 lines of production code
- Zero changes to
OptionsFactory,OptionsCache,UnnamedOptionsManager - Catches Patterns 1, 2, and 3 (the three most common misuse cases)
- Error message includes actionable guidance
TryAddSingletonensures only one guard perTOptionstype (idempotent)- Aligns with team consensus: throw on misuse
Cons:
- Does NOT catch Pattern 4 (non-hosted:
IAsyncStartupValidatoris registered but never called) - Service resolution in constructor (
GetService<IAsyncStartupValidator>), but only once per type at first access - If the developer registers a custom
IValidateOptions<T>before the guard,TryAddSingletonwon't register it (unlikely edge case)
Complexity: Low · Risk: Low · Value: High
internal sealed class AsyncValidationState
{
private readonly ConcurrentDictionary<(Type, string), bool> _validated = new();
public void MarkValidated(Type optionsType, string name)
=> _validated[(optionsType, name)] = true;
public bool HasBeenValidated(Type optionsType, string name)
=> _validated.TryGetValue((optionsType, name), out bool v) && v;
}
internal sealed class AsyncValidationGuard<TOptions> : IValidateOptions<TOptions>
where TOptions : class
{
private readonly AsyncValidationState _state;
public AsyncValidationGuard(AsyncValidationState state) => _state = state;
public ValidateOptionsResult Validate(string? name, TOptions options)
{
if (!_state.HasBeenValidated(typeof(TOptions), name ?? Options.DefaultName))
{
throw new InvalidOperationException(
$"Async validators for '{typeof(TOptions).Name}' have not been " +
$"executed. Ensure Host.StartAsync() completes before accessing " +
$"options, or add .ValidateOnStartAsync() to your configuration.");
}
return ValidateOptionsResult.Success;
}
}The AsyncStartupValidator marks types as validated after running each one via _state.MarkValidated(type, name).
Pros:
- Catches ALL four misuse patterns, including Pattern 4 (non-hosted)
- Catches ordering issues (accessing options before
Host.StartAsync()completes) - Per-type, per-name granularity
Cons:
- ~3 new files, ~120 lines
- Shared mutable state (
AsyncValidationState) across DI scopes - Phase transitions are tricky across hosting models (Generic Host, WebApplication, minimal hosting, custom hosts)
- Thread safety of the
ConcurrentDictionaryadds subtle complexity - Risk of false positives during host startup ordering (e.g., a
Configure<T>callback that resolvesIOptions<T>.ValueduringHost.StartAsync()but before the async validator runs)
Complexity: Medium · Risk: Medium · Value: High
Concept: When ValidateDataAnnotationsAsync() is called, also register a sync DataAnnotationValidateOptions<T> so the sync pipeline at least validates sync-only attributes. Requires patching the sync Validator to skip AsyncValidationAttribute.
public static OptionsBuilder<TOptions> ValidateDataAnnotationsAsync<TOptions>(
this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class
{
ArgumentNullException.ThrowIfNull(optionsBuilder);
// Async validator (for async pipeline)
optionsBuilder.Services.AddSingleton<IAsyncValidateOptions<TOptions>>(
new DataAnnotationValidateOptionsAsync<TOptions>(optionsBuilder.Name));
// Sync fallback (for sync pipeline, validates [Required], [Range], etc.)
// AsyncValidationAttributes are skipped by patched Validator.GetValidationErrors()
optionsBuilder.Services.TryAddSingleton<IValidateOptions<TOptions>>(
new DataAnnotationValidateOptions<TOptions>(optionsBuilder.Name));
return optionsBuilder;
}Requires adding an if (attr is AsyncValidationAttribute) continue; skip in Validator.GetValidationErrors() in System.ComponentModel.Annotations.
Pros:
- Sync attributes always validated regardless of startup configuration
- Graceful degradation: partial validation > no validation
Cons:
- Goes against team consensus (throw, not silently degrade)
- Async-only attributes are still silently skipped (not thrown, not validated)
- Creates confusing DX:
.ValidateDataAnnotationsAsync()implicitly registers sync validation the developer didn't ask for - Requires a change in
System.ComponentModel.Annotations(different package, different review) - The "skip async attrs in sync path" change has broader ecosystem implications
Complexity: Medium · Risk: Medium · Value: Medium (lower than A1 because it doesn't fail-fast)
Concept: Modify OptionsFactory<T> to inject IEnumerable<IAsyncValidateOptions<T>> and check whether any exist. If async validators are registered but IAsyncStartupValidator hasn't run, throw during Create().
public class OptionsFactory<TOptions> : IOptionsFactory<TOptions>
{
// ... existing fields ...
private readonly bool _hasAsyncValidators;
private readonly bool _hasAsyncStartupValidator;
public OptionsFactory(
IEnumerable<IConfigureOptions<TOptions>> setups,
IEnumerable<IPostConfigureOptions<TOptions>> postConfigures,
IEnumerable<IValidateOptions<TOptions>> validations,
IEnumerable<IAsyncValidateOptions<TOptions>> asyncValidations = null,
IAsyncStartupValidator asyncStartupValidator = null)
{
// ...
_hasAsyncValidators = asyncValidations?.Any() == true;
_hasAsyncStartupValidator = asyncStartupValidator is not null;
}
public TOptions Create(string name)
{
// ... existing configure + post-configure ...
if (_hasAsyncValidators && !_hasAsyncStartupValidator)
{
throw new InvalidOperationException(
$"Async validators are registered for '{typeof(TOptions).Name}' " +
"but no IAsyncStartupValidator is configured. " +
"Add .ValidateOnStartAsync() to your options configuration.");
}
// ... existing sync validation loop ...
}
}Pros:
- Guard runs at the exact point of failure (options creation)
- No new types needed (guard is inline in existing code)
- Catches Patterns 1, 2, and 3
Cons:
- Modifies
OptionsFactory, the one class the bypass strategy was designed to leave untouched - Changes the constructor signature (new parameters)
- DI resolution of
IAsyncValidateOptions<T>[]happens for ALL options types, even those without async validators (perf concern) - Still doesn't catch Pattern 4 (registered but never called)
- Higher blast radius than Options A1/A2
- Violates the "Bypass, Don't Infect" principle: the factory now knows about async validators
Complexity: Medium-High · Risk: Medium-High · Value: High
Concept: Instead of a runtime guard, create a Roslyn analyzer that detects .ValidateDataAnnotationsAsync() or .ValidateAsync() without a corresponding .ValidateOnStartAsync() in the same fluent chain.
// Analyzer rule: OPTS001
// "ValidateDataAnnotationsAsync() or ValidateAsync() called without
// ValidateOnStartAsync() — async validators will never execute"
// Would flag this:
builder.Services.AddOptions<MyOpts>()
.BindConfiguration("Section")
.ValidateDataAnnotationsAsync(); // ⚠️ OPTS001
// Would NOT flag this:
builder.Services.AddOptions<MyOpts>()
.BindConfiguration("Section")
.ValidateDataAnnotationsAsync()
.ValidateOnStartAsync(); // ✅Pros:
- Catches misuse at build time, before any code runs
- Zero runtime overhead
- Actionable warning with fix suggestion
- Does not modify any production code
Cons:
- Does not protect at runtime: if the user ignores/suppresses the warning, silent failure still occurs
- Cannot detect Pattern 4 (non-hosted scenario)
- Fluent chain analysis is non-trivial in Roslyn (calls may be split across methods, files, or conditional branches)
- Requires shipping a new analyzer package
- Build-time analysis is brittle for DI patterns (registrations may be in extension methods, across assemblies, etc.)
- Does not address the runtime pit-of-failure, only developer education
Complexity: Medium · Risk: Low · Value: Medium (complementary, not standalone)
Concept: Make ValidateDataAnnotations() automatically register both sync and async validators. Make ValidateOnStart() automatically trigger both pipelines. The guard becomes unnecessary because the existing APIs "just work" for async.
// Developer writes (unchanged API surface):
builder.Services.AddOptions<SmtpSettings>()
.ValidateDataAnnotations() // auto-registers BOTH pipelines
.ValidateOnStart(); // auto-triggers BOTH pipelines
// Under the hood:
// ValidateDataAnnotations() →
// registers IValidateOptions<T> (sync, skips AsyncValidationAttribute)
// registers IAsyncValidateOptions<T> (async, handles all attrs)
//
// ValidateOnStart() →
// registers IStartupValidator (sync)
// registers IAsyncStartupValidator (async, if IAsyncValidateOptions<T> present)Pros:
- Eliminates the pit-of-failure entirely: no separate async API to forget
- Best DX: developers don't need to know about the sync/async split
- Backward compatible: types without async attrs behave identically
Cons:
- Requires the sync
Validator.GetValidationErrors()patch to skipAsyncValidationAttribute(~2 lines, but inSystem.ComponentModel.Annotations) - Semantic change:
ValidateDataAnnotations()now does more than before - Types with only async attrs would have an empty sync validator (harmless but could confuse diagnostic tooling)
- Larger scope of change: modifies existing method behavior, not just adding new code
- If rejected, the explicit async APIs still need a guard
- May conflict with API review expectations (reviewers may prefer explicit separate APIs)
Complexity: Medium · Risk: Medium · Value: Very High (if accepted)
Pattern 1 Pattern 2 Pattern 3 Pattern 4 Complexity Aligns w/ Modifies
Forgot Wrong Lambda Non-hosted (LOC) Consensus? Factory?
OnStart OnStart no trigger
Async (sync)
────────────────────────────────────────────────────────────────────────────────────────────────────────────
A1: Registration ✅ Throw ✅ Throw ✅ Throw ❌ ~40 ✅ Yes ❌ No
Guard (simple)
A2: Lifecycle ✅ Throw ✅ Throw ✅ Throw ✅ Throw ~120 ✅ Yes ❌ No
Guard (stateful)
B: Dual Registration ⚠️ Partial ⚠️ Partial ❌ ❌ ~30+patch ❌ No ❌ No
(sync fallback) (sync only) (sync only) (Validator)
C: Factory ✅ Throw ✅ Throw ✅ Throw ❌ ~40 ✅ Yes ✅ YES
Awareness (bad)
D: Analyzer ✅ Warn ✅ Warn ✅ Warn ❌ ~200+ ⚠️ Partial ❌ No
(build-time) (analyzer)
E: Unified ✅ N/A ✅ N/A ✅ N/A ⚠️ Partial ~60+patch ✅ Yes ❌ No
Registration (no pit) (no pit) (no pit) (partial) (Validator)
Rationale:
- Highest value-to-risk ratio. ~40 lines, zero changes to core infrastructure (
OptionsFactory,OptionsCache,UnnamedOptionsManager). Aligns with the "Bypass, Don't Infect" strategy. - Directly implements team consensus. The guard throws
InvalidOperationExceptionwhen async validators exist butIAsyncStartupValidatorisn't registered. - Catches the three most common misuse patterns (1, 2, 3). Pattern 4 (non-hosted) is rare and inherently the developer's responsibility: they're manually building the DI container and must call
IAsyncStartupValidator.ValidateAsync()themselves. - Minimal blast radius. New file, new registrations via
TryAddSingleton, existing code paths unchanged. - Actionable error message. Tells the developer exactly what to add (
.ValidateOnStartAsync()).
An analyzer can complement the runtime guard by catching misuse at build time. However, it's a follow-up item, not blocking for .NET 11:
- Analyzers require a separate package and shipping vehicle
- Fluent chain analysis is non-trivial
- The runtime guard is the safety net regardless
Gap 2 ("accessed before async startup completes") is the ordering edge case where a hosted service or Configure<T> callback resolves IOptions<T>.Value during Host.StartAsync() but before IAsyncStartupValidator.ValidateAsync() runs. The instance gets cached without async validation.
Documentation is sufficient for Gap 2. The team agreed this is a rare edge case that requires a specific and avoidable coding pattern. The following must be documented:
-
XML docs on
ValidateOnStartAsync(): Add a<remarks>noting that options types registered withValidateOnStartAsync()must not be resolved viaIOptions<T>.ValueorIOptionsMonitor<T>.Get()duringConfigure<T>,PostConfigure<T>, or earlyIHostedService.StartAsync()callbacks that execute before async startup validation completes. -
XML docs on
ValidateDataAnnotationsAsync(): Add a<remarks>noting that async validation attributes are only evaluated duringHost.StartAsync()viaValidateOnStartAsync(), not during lazyIOptions<T>.Valueaccess orIOptionsMonitor<T>config reload. -
API proposal "Risks" section: Add explicit guidance that
IOptions<T>.Valuefor async-validated types should not be resolved insideConfigure<T>callbacks,PostConfigure<T>callbacks, orIHostedService.StartAsync()implementations that run before the async startup validator. The recommended pattern is to injectIOptionsMonitor<T>and access.CurrentValueonly after startup completes.
This documentation approach is consistent with how the existing sync ValidateOnStart() handles similar ordering concerns: it relies on correct usage, not runtime enforcement.
This is an initial, opt-in async effort for adding async validation support to the Options pipeline. These gaps are architectural constraints of the existing sync IOptions<T>/IOptionsMonitor<T> interfaces, not temporary v1 trade-offs. Follow-up APIs (e.g., IAsyncOptions<T>, IAsyncOptionsMonitor<T>) are expected to address them incrementally; none should block this proposal.
| Gap | Severity | Disposition |
|---|---|---|
Gap 1: No host / no ValidateOnStartAsync(), async validators silently skipped |
🔴 High | Option A1 guard (this document) |
Gap 2: Options accessed before IAsyncStartupValidator runs during startup |
🟡 Medium | Documentation: XML docs on ValidateOnStartAsync()/ValidateDataAnnotationsAsync() |
Gap 3: Config reload, IOptionsMonitor only runs sync validators on change |
🟡 Medium | Deferred: workaround is IOptionsMonitor.OnChange + Validator.TryValidateObjectAsync |
Gap 4: No IAsyncOptions<T> for lazy async resolution on first access |
🟢 Low | Deferred: requires IAsyncOptions<T> with GetAsync(), intersects with async DI |
Gap 5: IOptionsSnapshot<T> per-scope, no async validation per request |
🟢 Low | Deferred: requires IAsyncOptionsSnapshot<T> |
A2 (lifecycle tracking) catches Pattern 4 and Gap 2 but introduces shared mutable state (AsyncValidationState) and coupling between the startup validator, the guard, and the DI container timing. Getting phase transitions right across Generic Host, WebApplication, minimal hosting, and custom hosts is complex and error-prone. The marginal benefit (catching these rare edge cases) doesn't justify the risk for .NET 11.
Goes against team consensus (throw, don't silently degrade). Dual registration also creates confusing DX where .ValidateDataAnnotationsAsync() implicitly does sync validation.
Violates "Bypass, Don't Infect": the factory now imports IAsyncValidateOptions<T>[] and IAsyncStartupValidator. The bypass strategy's core invariant is that OptionsFactory has zero awareness of async validation.
Strategy E (unified registration) is the ideal long-term direction but is a larger scope change that modifies existing method semantics and requires the Validator.GetValidationErrors() patch in System.ComponentModel.Annotations. It may face pushback in API review. A1 is the right guard regardless: even if E ships, non-unified registrations (ValidateDataAnnotationsAsync() alone) need runtime protection.
If Strategy E (unified registration) is later adopted, Option A1 remains compatible:
Current state (explicit APIs):
.ValidateDataAnnotationsAsync() → registers guard + async validator
.ValidateOnStartAsync() → registers IAsyncStartupValidator (guard passes)
Future state (unified APIs, Strategy E):
.ValidateDataAnnotations() → registers sync + async validators + guard
.ValidateOnStart() → registers sync + async startup validators (guard passes)
Explicit APIs still available:
.ValidateDataAnnotationsAsync() → guard still protects if used standalone
The guard is forward-compatible with unification. It becomes vestigial (always passes) under Strategy E but doesn't break anything.
| File | Change | Lines |
|---|---|---|
Microsoft.Extensions.Options/src/AsyncValidationGuard.cs |
NEW | ~45 |
Microsoft.Extensions.Options.DataAnnotations/src/OptionsBuilderDataAnnotationsExtensions.cs |
Add guard registration in ValidateDataAnnotationsAsync() |
+5 |
Microsoft.Extensions.Options/src/OptionsBuilder.cs |
Add guard registration in each ValidateAsync() overload (6 overloads × 3 lines) |
+18 |
Microsoft.Extensions.Options/tests/.../OptionsValidationTests.cs |
Add test cases | +50 |
| Subtotal (guard) | ~118 |
No changes to: OptionsFactory.cs, OptionsCache.cs, UnnamedOptionsManager.cs
[Fact]
public void ValidateDataAnnotationsAsync_WithoutValidateOnStartAsync_ThrowsOnAccess()
{
var services = new ServiceCollection();
services.AddOptions<TestOptions>()
.Configure(o => o.Value = "test")
.ValidateDataAnnotationsAsync();
using var sp = services.BuildServiceProvider();
var options = sp.GetRequiredService<IOptions<TestOptions>>();
var ex = Assert.Throws<InvalidOperationException>(() => options.Value);
Assert.Contains("ValidateOnStartAsync", ex.Message);
Assert.Contains(nameof(TestOptions), ex.Message);
}
[Fact]
public async Task ValidateDataAnnotationsAsync_WithValidateOnStartAsync_Succeeds()
{
var services = new ServiceCollection();
services.AddOptions<TestOptions>()
.Configure(o => o.Value = "test")
.ValidateDataAnnotationsAsync()
.ValidateOnStartAsync();
using var sp = services.BuildServiceProvider();
var options = sp.GetRequiredService<IOptions<TestOptions>>();
// Guard passes: async startup validator is registered
var value = options.Value;
Assert.Equal("test", value.Value);
}
[Fact]
public void ValidateAsync_Lambda_WithoutValidateOnStartAsync_ThrowsOnAccess()
{
var services = new ServiceCollection();
services.AddOptions<TestOptions>()
.Configure(o => o.Value = "test")
.ValidateAsync(async (opts, ct) => true, "always passes");
using var sp = services.BuildServiceProvider();
var options = sp.GetRequiredService<IOptions<TestOptions>>();
var ex = Assert.Throws<InvalidOperationException>(() => options.Value);
Assert.Contains("ValidateOnStartAsync", ex.Message);
}
[Fact]
public void ValidateDataAnnotations_Sync_DoesNotRegisterGuard()
{
var services = new ServiceCollection();
services.AddOptions<TestOptions>()
.Configure(o => o.Value = "test")
.ValidateDataAnnotations(); // sync-only, no guard needed
using var sp = services.BuildServiceProvider();
var options = sp.GetRequiredService<IOptions<TestOptions>>();
// Should not throw: no async validators, no guard
var value = options.Value;
Assert.Equal("test", value.Value);
}
public class TestOptions
{
public string Value { get; set; } = "";
}- Gap Analysis: ViveliDuCh/a4a765a
- API Proposal: dotnet/runtime#128100
- Prototype branch: ViveliDuCh/runtime (async-validation)