-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Add Eager Options Validation: ValidateOnStart API #47821
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
+651
−4
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
6b57182
Add Options Validation on Start
maryamariyan 2d6a5d9
Apply PR feedback:
maryamariyan 68e1b66
Cleanup test class
maryamariyan 1c2c367
Rename
maryamariyan 8effbfc
Move to hosting assembly
maryamariyan 9107eab
- Locate tests properly:
maryamariyan 1f36ad3
fix compile
maryamariyan 6594f84
Apply PR feedback. Improve unit tests
maryamariyan 23b6ea3
Apply nit feedback
maryamariyan 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
There are no files selected for viewing
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
40 changes: 40 additions & 0 deletions
40
src/libraries/Microsoft.Extensions.Hosting/src/OptionsBuilderExtensions.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,40 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using Microsoft.Extensions.Options; | ||
|
|
||
| namespace Microsoft.Extensions.DependencyInjection | ||
| { | ||
| /// <summary> | ||
| /// Extension methods for adding configuration related options services to the DI container via <see cref="OptionsBuilder{TOptions}"/>. | ||
| /// </summary> | ||
| public static class OptionsBuilderExtensions | ||
| { | ||
| /// <summary> | ||
| /// Enforces options validation check on start rather than in runtime. | ||
| /// </summary> | ||
| /// <typeparam name="TOptions">The type of options.</typeparam> | ||
| /// <param name="optionsBuilder">The <see cref="OptionsBuilder{TOptions}"/> to configure options instance.</param> | ||
| /// <returns>The <see cref="OptionsBuilder{TOptions}"/> so that additional calls can be chained.</returns> | ||
| public static OptionsBuilder<TOptions> ValidateOnStart<TOptions>(this OptionsBuilder<TOptions> optionsBuilder) | ||
| where TOptions : class | ||
| { | ||
| if (optionsBuilder == null) | ||
| { | ||
| throw new ArgumentNullException(nameof(optionsBuilder)); | ||
| } | ||
|
|
||
| optionsBuilder.Services.AddHostedService<ValidationHostedService>(); | ||
| optionsBuilder.Services.AddOptions<ValidatorOptions>() | ||
| .Configure<IOptionsMonitor<TOptions>>((vo, options) => | ||
| { | ||
| // This adds an action that resolves the options value to force evaluation | ||
| // We don't care about the result as duplicates are not important | ||
| vo.Validators[typeof(TOptions)] = () => options.Get(optionsBuilder.Name); | ||
| }); | ||
|
|
||
| return optionsBuilder; | ||
| } | ||
| } | ||
| } |
57 changes: 57 additions & 0 deletions
57
src/libraries/Microsoft.Extensions.Hosting/src/ValidationHostedService.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,57 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Runtime.ExceptionServices; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Hosting; | ||
| using Microsoft.Extensions.Options; | ||
|
|
||
| namespace Microsoft.Extensions.DependencyInjection | ||
| { | ||
| internal class ValidationHostedService : IHostedService | ||
| { | ||
| private readonly IDictionary<Type, Action> _validators; | ||
|
|
||
| public ValidationHostedService(IOptions<ValidatorOptions> validatorOptions) | ||
| { | ||
| _validators = validatorOptions?.Value?.Validators ?? throw new ArgumentNullException(nameof(validatorOptions)); | ||
| } | ||
|
|
||
| public Task StartAsync(CancellationToken cancellationToken) | ||
| { | ||
| var exceptions = new List<Exception>(); | ||
|
|
||
| foreach (var validate in _validators.Values) | ||
| { | ||
| try | ||
| { | ||
| // Execute the validation method and catch the validation error | ||
| validate(); | ||
| } | ||
| catch (OptionsValidationException ex) | ||
| { | ||
| exceptions.Add(ex); | ||
| } | ||
| } | ||
|
|
||
| if (exceptions.Count == 1) | ||
| { | ||
| // Rethrow if it's a single error | ||
| ExceptionDispatchInfo.Capture(exceptions[0]).Throw(); | ||
| } | ||
|
|
||
| if (exceptions.Count > 1) | ||
| { | ||
| // Aggregate if we have many errors | ||
| throw new AggregateException(exceptions); | ||
| } | ||
|
|
||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; | ||
| } | ||
| } |
14 changes: 14 additions & 0 deletions
14
src/libraries/Microsoft.Extensions.Hosting/src/ValidatorOptions.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,14 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
|
|
||
| namespace Microsoft.Extensions.DependencyInjection | ||
| { | ||
| internal class ValidatorOptions | ||
| { | ||
| // Maps each options type to a method that forces its evaluation, e.g. IOptionsMonitor<TOptions>.Get(name) | ||
| public IDictionary<Type, Action> Validators { get; } = new Dictionary<Type, Action>(); | ||
| } | ||
| } | ||
50 changes: 50 additions & 0 deletions
50
src/libraries/Microsoft.Extensions.Hosting/tests/UnitTests/ComplexOptions.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,50 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
|
|
||
| namespace Microsoft.Extensions.Hosting.Tests | ||
| { | ||
| public class ComplexOptions | ||
| { | ||
| public ComplexOptions() | ||
| { | ||
| Nested = new NestedOptions(); | ||
| Virtual = "complex"; | ||
| } | ||
| public NestedOptions Nested { get; set; } | ||
| public int Integer { get; set; } | ||
| public bool Boolean { get; set; } | ||
| public virtual string Virtual { get; set; } | ||
|
|
||
| public string PrivateSetter { get; private set; } | ||
| public string ProtectedSetter { get; protected set; } | ||
| public string InternalSetter { get; internal set; } | ||
| public static string StaticProperty { get; set; } | ||
|
|
||
| public string ReadOnly | ||
| { | ||
| get { return null; } | ||
| } | ||
| } | ||
|
|
||
| public class NestedOptions | ||
| { | ||
| public int Integer { get; set; } | ||
| } | ||
|
|
||
| public class DerivedOptions : ComplexOptions | ||
| { | ||
| public override string Virtual | ||
| { | ||
| get | ||
| { | ||
| return base.Virtual; | ||
| } | ||
| set | ||
| { | ||
| base.Virtual = "Derived:" + value; | ||
| } | ||
| } | ||
| } | ||
| } |
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.