Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ public OptionsBuilder(Microsoft.Extensions.DependencyInjection.IServiceCollectio
public virtual Microsoft.Extensions.Options.OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3>(System.Action<TOptions, TDep1, TDep2, TDep3> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class { throw null; }
public virtual Microsoft.Extensions.Options.OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4>(System.Action<TOptions, TDep1, TDep2, TDep3, TDep4> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class { throw null; }
public virtual Microsoft.Extensions.Options.OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4, TDep5>(System.Action<TOptions, TDep1, TDep2, TDep3, TDep4, TDep5> configureOptions) where TDep1 : class where TDep2 : class where TDep3 : class where TDep4 : class where TDep5 : class { throw null; }
public virtual Microsoft.Extensions.Options.OptionsBuilder<TOptions> Validate<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors)] TValidateOptions>() where TValidateOptions : class, Microsoft.Extensions.Options.IValidateOptions<TOptions> { throw null; }
public virtual Microsoft.Extensions.Options.OptionsBuilder<TOptions> Validate(System.Func<TOptions, bool> validation) { throw null; }
public virtual Microsoft.Extensions.Options.OptionsBuilder<TOptions> Validate(System.Func<TOptions, bool> validation, string failureMessage) { throw null; }
public virtual Microsoft.Extensions.Options.OptionsBuilder<TOptions> Validate<TDep>(System.Func<TOptions, TDep, bool> validation) where TDep : notnull { throw null; }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// 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.Options
{
internal sealed class NamedValidateOptionsFilter<TOptions, TInner> : IValidateOptions<TOptions>
where TOptions : class
where TInner : IValidateOptions<TOptions>
{
private readonly string _name;
private readonly TInner _inner;

internal NamedValidateOptionsFilter(string name, TInner inner)
{
ArgumentNullException.ThrowIfNull(inner);

_name = name;
_inner = inner;
}

public ValidateOptionsResult Validate(string? name, TOptions options)
{
if (name == _name)
Comment thread
89netraM marked this conversation as resolved.
Outdated
{
return _inner.Validate(name, options);
}

// ignored if not validating this instance
return ValidateOptionsResult.Skip;
}
}
}
14 changes: 14 additions & 0 deletions src/libraries/Microsoft.Extensions.Options/src/OptionsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.Extensions.Options
Expand Down Expand Up @@ -335,6 +336,19 @@ public virtual OptionsBuilder<TOptions> PostConfigure<TDep1, TDep2, TDep3, TDep4
return this;
}

/// <summary>
/// Registers an <see cref="IValidateOptions{TOptions}"/> type for an options type.
/// </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>()
Comment thread
tarekgh marked this conversation as resolved.
Comment thread
89netraM marked this conversation as resolved.
where TValidateOptions : class, IValidateOptions<TOptions>
{
Services.AddTransient<IValidateOptions<TOptions>>(sp =>
new NamedValidateOptionsFilter<TOptions, TValidateOptions>(Name, ActivatorUtilities.GetServiceOrCreateInstance<TValidateOptions>(sp)));
return this;
}

/// <summary>
/// Registers a validation action for an options type using a default failure message.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -814,5 +814,96 @@ public void ValidateOnStart_ConfigureBasedOnDataAnnotationRestrictions_Validatio

Assert.NotNull(value);
}

[Fact]
Comment thread
tarekgh marked this conversation as resolved.
public void ValidateWithValidatorType_ValidatesFailureCorrectly()
{
var services = new ServiceCollection();
services.AddOptions<ComplexOptions>()
.Configure(o => o.Boolean = false)
.Validate<ComplexOptionsValidator>();

var sp = services.BuildServiceProvider();

var error = Assert.Throws<OptionsValidationException>(() => sp.GetRequiredService<IOptions<ComplexOptions>>().Value);
ValidateFailure<ComplexOptions>(error, Options.DefaultName, 1, "Boolean != true");
}

[Fact]
public void ValidateWithValidatorType_ValidationSuccessful()
{
var services = new ServiceCollection();
services.AddOptions<ComplexOptions>()
.Configure(o => o.Boolean = true)
.Validate<ComplexOptionsValidator>();

var sp = services.BuildServiceProvider();

var value = sp.GetRequiredService<IOptions<ComplexOptions>>().Value;

Assert.NotNull(value);
}

[Fact]
public void ValidateWithValidatorType_WithDependencies_ValidationSuccessful()
{
var services = new ServiceCollection();
var dependency = new ObservableDependency();
services.AddSingleton(dependency);
services.AddOptions<FakeOptions>()
.Validate<FakeOptionsValidatorWithDependencies>();

var sp = services.BuildServiceProvider();

var value = sp.GetRequiredService<IOptions<FakeOptions>>().Value;

Assert.NotNull(value);
Assert.True(dependency.HasBeenCalled);
}

private class FakeOptionsValidatorWithDependencies(ObservableDependency dependency) : IValidateOptions<FakeOptions>
{
public ValidateOptionsResult Validate(string? name, FakeOptions options)
{
dependency.Call();
return ValidateOptionsResult.Success;
}
}

private class ObservableDependency
{
public bool HasBeenCalled { get; private set; } = false;
Comment thread
89netraM marked this conversation as resolved.
Outdated

public void Call()
{
HasBeenCalled = true;
}
}

[Fact]
public void ValidateWithValidatorType_AreScopedToNamedOptions()
{
var services = new ServiceCollection();

services.AddOptions<ComplexOptions>("invalid")
.Configure(o => o.Boolean = false);

// ComplexOptionsValidator is only added to the valid option
services.AddOptions<ComplexOptions>("valid")
.Configure(o => o.Boolean = true)
.Validate<ComplexOptionsValidator>();

var sp = services.BuildServiceProvider();

var monitor = sp.GetRequiredService<IOptionsMonitor<ComplexOptions>>();

// "valid" passes — Boolean is true, validator runs and succeeds
var valid = monitor.Get("valid");
Assert.NotNull(valid);

// "invalid" passes — validator is scoped to "valid", so it skips "invalid"
var invalid = monitor.Get("invalid");
Assert.NotNull(invalid);
}
Comment thread
tarekgh marked this conversation as resolved.
Comment thread
89netraM marked this conversation as resolved.
}
}
Loading