-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Add async DataAnnotations bridge for Microsoft.Extensions.Options #129218
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ViveliDuCh
merged 2 commits into
dotnet:main
from
ViveliDuCh:async-options-dataannotations-v2
Jun 12, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
13 changes: 13 additions & 0 deletions
13
...ensions.Options.DataAnnotations/ref/Microsoft.Extensions.Options.DataAnnotations.Async.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
| // ------------------------------------------------------------------------------ | ||
| // Changes to this file must follow the https://aka.ms/api-review process. | ||
| // ------------------------------------------------------------------------------ | ||
|
|
||
| namespace Microsoft.Extensions.Options | ||
| { | ||
| public partial class DataAnnotationValidateOptions<TOptions> : Microsoft.Extensions.Options.IAsyncValidateOptions<TOptions> | ||
| { | ||
| public System.Threading.Tasks.Task<Microsoft.Extensions.Options.ValidateOptionsResult> ValidateAsync(string? name, TOptions options, System.Threading.CancellationToken cancellationToken = default) { throw null; } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
156 changes: 156 additions & 0 deletions
156
...s/Microsoft.Extensions.Options.DataAnnotations/src/DataAnnotationValidateOptions.Async.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| #if NET11_0_OR_GREATER | ||
|
|
||
| using System; | ||
| using System.Collections; | ||
| using System.Collections.Generic; | ||
| using System.ComponentModel.DataAnnotations; | ||
| using System.Diagnostics; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Reflection; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace Microsoft.Extensions.Options | ||
| { | ||
| /// <summary> | ||
| /// Async validation implementation for <see cref="DataAnnotationValidateOptions{TOptions}"/>. | ||
| /// </summary> | ||
| public partial class DataAnnotationValidateOptions<TOptions> | ||
| { | ||
| /// <summary> | ||
| /// Asynchronously validates a specific named options instance (or all when <paramref name="name"/> is null). | ||
| /// </summary> | ||
| /// <param name="name">The name of the options instance being validated.</param> | ||
| /// <param name="options">The options instance.</param> | ||
| /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> | ||
| /// <returns>The <see cref="ValidateOptionsResult"/> result.</returns> | ||
| /// <remarks> | ||
| /// The <paramref name="cancellationToken"/> is propagated from | ||
| /// <c>Host.StartAsync(CancellationToken)</c>. By default, no startup timeout | ||
| /// is applied. Configure <c>HostOptions.StartupTimeout</c> or pass | ||
| /// a <see cref="CancellationToken"/> with a timeout to <c>Host.StartAsync</c> | ||
| /// to bound I/O-bound async validators: | ||
| /// <code> | ||
| /// builder.Services.Configure<HostOptions>(opts => | ||
| /// opts.StartupTimeout = TimeSpan.FromSeconds(30)); | ||
| /// </code> | ||
| /// </remarks> | ||
| [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", | ||
| Justification = "Suppressing the warnings on this method since the constructor of the type is annotated as RequiresUnreferencedCode.")] | ||
|
eiriktsarpalis marked this conversation as resolved.
|
||
| public async Task<ValidateOptionsResult> ValidateAsync(string? name, TOptions options, CancellationToken cancellationToken = default) | ||
| { | ||
| // Null name is used to configure all named options. | ||
| if (Name is not null && Name != name) | ||
| { | ||
| // Ignored if not validating this instance. | ||
| return ValidateOptionsResult.Skip; | ||
| } | ||
|
|
||
| // Ensure options are provided to validate against | ||
| ArgumentNullException.ThrowIfNull(options); | ||
|
ViveliDuCh marked this conversation as resolved.
|
||
|
|
||
| var validationResults = new List<ValidationResult>(); | ||
| HashSet<object>? visited = null; | ||
| List<string>? errors = null; | ||
|
|
||
| (bool success, errors) = await TryValidateOptionsAsync(options, options.GetType().Name, validationResults, errors, visited, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (success) | ||
| { | ||
| return ValidateOptionsResult.Success; | ||
| } | ||
|
|
||
| Debug.Assert(errors is not null && errors.Count > 0); | ||
|
|
||
| return ValidateOptionsResult.Fail(errors); | ||
| } | ||
|
|
||
| /// <remarks> | ||
| /// Async counterpart of <see cref="TryValidateOptions"/>. Uses a tuple return | ||
| /// <c>(bool success, List<string>? errors)</c> instead of <c>ref</c> parameters | ||
| /// because <c>async</c> methods cannot have <c>ref</c>/<c>out</c> parameters. | ||
| /// | ||
| /// <c>visited</c> does not need to be returned — it is created <em>before</em> each | ||
| /// recursive call, so the callee always receives a non-null, shared instance. | ||
| /// <c>errors</c> must be returned because it may be lazily created | ||
| /// (<c>errors ??= new List<string>()</c>) inside the callee. | ||
| /// </remarks> | ||
| [RequiresUnreferencedCode("This method on this type will walk through all properties of the passed in options object, and its type cannot be " + | ||
| "statically analyzed so its members may be trimmed.")] | ||
| private static async Task<(bool success, List<string>? errors)> TryValidateOptionsAsync( | ||
|
ViveliDuCh marked this conversation as resolved.
|
||
| object options, | ||
| string qualifiedName, | ||
| List<ValidationResult> results, | ||
| List<string>? errors, | ||
| HashSet<object>? visited, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| Debug.Assert(options is not null); | ||
|
|
||
| if (visited is not null && visited.Contains(options)) | ||
| { | ||
| return (true, errors); | ||
| } | ||
|
|
||
| results.Clear(); | ||
|
|
||
| bool res = await Validator.TryValidateObjectAsync(options, new ValidationContext(options), results, validateAllProperties: true, cancellationToken).ConfigureAwait(false); | ||
| if (!res) | ||
|
ViveliDuCh marked this conversation as resolved.
|
||
| { | ||
| errors ??= new List<string>(); | ||
|
|
||
| foreach (ValidationResult result in results) | ||
| { | ||
| errors.Add($"DataAnnotation validation failed for '{qualifiedName}' members: '{string.Join(",", result.MemberNames)}' with the error: '{result.ErrorMessage}'."); | ||
| } | ||
| } | ||
|
|
||
| foreach (PropertyInfo propertyInfo in options.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) | ||
| { | ||
| // Indexers are properties which take parameters. Ignore them. | ||
| if (propertyInfo.GetMethod is null || propertyInfo.GetMethod.GetParameters().Length > 0) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| object? value = propertyInfo.GetValue(options); | ||
|
|
||
| if (value is null) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| if (propertyInfo.GetCustomAttribute<ValidateObjectMembersAttribute>() is not null) | ||
| { | ||
| visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance); | ||
| visited.Add(options); | ||
|
|
||
| bool innerRes; | ||
| (innerRes, errors) = await TryValidateOptionsAsync(value, $"{qualifiedName}.{propertyInfo.Name}", results, errors, visited, cancellationToken).ConfigureAwait(false); | ||
| res = innerRes && res; | ||
| } | ||
| else if (value is IEnumerable enumerable && | ||
| propertyInfo.GetCustomAttribute<ValidateEnumeratedItemsAttribute>() is not null) | ||
| { | ||
| visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance); | ||
| visited.Add(options); | ||
|
|
||
| int index = 0; | ||
| foreach (object item in enumerable) | ||
| { | ||
| bool innerRes; | ||
| (innerRes, errors) = await TryValidateOptionsAsync(item, $"{qualifiedName}.{propertyInfo.Name}[{index++}]", results, errors, visited, cancellationToken).ConfigureAwait(false); | ||
| res = innerRes && res; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return (res, errors); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #endif | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.