Add a fluent Validate overload for adding validator types#127264
Add a fluent Validate overload for adding validator types#12726489netraM wants to merge 2 commits intodotnet:mainfrom
Validate overload for adding validator types#127264Conversation
Adds a Validate overload to the OptionsBuilder that registers an IValidateOptions type that validates the option type.
|
Tagging subscribers to this area: @dotnet/area-extensions-options |
| /// </summary> | ||
| /// <typeparam name="TValidateOptions">The validation type.</typeparam> | ||
| /// <returns>The current <see cref="OptionsBuilder{TOptions}"/>.</returns> | ||
| public virtual OptionsBuilder<TOptions> Validate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TValidateOptions>() |
There was a problem hiding this comment.
The existing Func<>-based Validate overloads pass Name to ValidateOptions, so validation is scoped to the OptionsBuilder's named option:
// Only validates option named "A"
services.AddOptions<MyOpts>("A").Validate(o => o.X > 0);The new Validate() registers the type directly; the validator sees all option names, not just the one on this builder. Whether it filters by name is entirely up to TValidateOptions. This is inherent to the IValidateOptions<T> interface design, but it's a behavioral difference users might not expect from a method sitting alongside the name-scoped overloads.
| Assert.NotNull(value); | ||
| } | ||
|
|
||
| [Fact] |
There was a problem hiding this comment.
Could you add a couple more test cases?
-
Validator with constructor-injected dependencies; this is the key scenario the API enables (e.g., [OptionsValidator]-generated types) and would exercise the DynamicallyAccessedMembers(PublicConstructors) annotation. Something like a validator that takes an ILogger or a custom service in its constructor.
-
Named options; verify behavior when the OptionsBuilder is configured with a non-default name (e.g.,
AddOptions<ComplexOptions>("myName")). Since unlike the Func<>-based Validate overloads, this method doesn't scope to the builder's Name, it would be good to have a test that documents this behavior explicitly.
Adds a
Validateoverload to theOptionsBuilderthat registers anIValidateOptionstype that validates the option type.Closes #115200