Validates ASP NET Core IOptions at startup via FluentValidation. If the options are not valid, will throw an exception detailing what's wrong with the options and stop the app's execution.
Aragas.Extensions.Options.FluentValidation can be installed using the Nuget Package Manager or the dotnet CLI.
# NuGet Package Manager
Install-Package Aragas.Extensions.Options.FluentValidation
# dotnet CLI
dotnet add package Aragas.Extensions.Options.FluentValidation
Simply change the code you most likely used to do like this:
public sealed class SomeOptionsValidator : AbstractValidator<SomeOptions>
{
public SomeOptionsValidator()
{
RuleFor(x => x.Host).IsUri().IsUrlTcpEndpointAvailable().When(x => x.Enabled);
}
}
public sealed record SomeOptions
{
public bool Enabled { get; init; } = default!;
public string Host { get; init; } = default!;
}
// Old code
services.Configure<SomeOptions>(ctx.Configuration.GetSection("SomeOptions"));
// New code
services.AddValidatedOptions<SomeOptions, SomeOptionsValidator>(ctx.Configuration.GetSection("SomeOptions"));
You can inject and configure a HttpClient in the validator
public sealed class SomeHttpOptionsValidator : AbstractValidator<SomeHttpOptions>
{
public SomeOptionsValidator(HttpClient client)
{
RuleFor(x => x.Url).IsUri().IsUrlAvailable(client).When(x => x.Enabled);
}
}
public sealed record SomeHttpOptions
{
public bool Enabled { get; init; } = default!;
public string Url { get; init; } = default!;
}
// Old code
services.Configure<SomeOptions>(ctx.Configuration.GetSection("SomeHttpOptions"));
// New code
services.AddValidatedOptionsWithHttp<SomeOptions, SomeOptionsValidator>(ctx.Configuration.GetSection("SomeHttpOptions"), httpBuilder =>
{
httpBuilder.ConfigureHttpClient(client =>
{
client.Timeout = TimeSpan.FromSeconds(30);
});
});
You can inject a custom dependency and easily retrieve it in the validator
public sealed class CustomService
{
public bool IsValid(string str) => str.Contains("Hello World!");
}
public sealed class SomeDIOptionsValidator : AbstractValidator<SomeDIOptions>
{
public SomeDIOptionsValidator(CustomService cs)
{
RuleFor(x => x.Url).IsUri().When(x => cs.IsValid(x.ToVerify));
}
}
public sealed record SomeDIOptions
{
public string ToVerify { get; init; } = default!;
public string Url { get; init; } = default!;
}
// Old code
services.Configure<SomeDIOptions>(ctx.Configuration.GetSection("SomeDIOptions"));
// New code
services.AddTransient<CustomService>();
services.AddValidatedOptions<SomeDIOptions, SomeDIOptionsValidator>(ctx.Configuration.GetSection("SomeDIOptions"));