Adds strongly typed IOptions<T> binding, with Fluent Validation and shared appsettings for the Web client app

This commit is contained in:
BinaryAlley committed 2024-09-07 17:11:53 +03:00
1 parent cf7981aad4
commit d8c64920dc
6 files changed
+153 -1

No files matched your search

@@ -35,7 +35,7 @@ public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TReques
/// </summary>
/// <param name="request">Incoming request.</param>
/// <param name="next">Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask<TResponse> Handle(TRequest request, CancellationToken cancellationToken, MessageHandlerDelegate<TRequest, TResponse> next)
{
// if there is no validator, just invoke the handler
@@ -0,0 +1,23 @@
namespace Lumina.Presentation.Web.Common.Models.Configuration;
/// <summary>
/// Model for deserializing server configuration settings.
/// </summary>
public class ServerConfigurationModel
{
#region ================================================================== FIELD MEMBERS ================================================================================
public const string SectionName = "ServerConfiguration";
#endregion
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets or sets the remote API server path.
/// </summary>
public required string BaseAddress { get; init; }
/// <summary>
/// Gets or sets the remote API server port.
/// </summary>
public required ushort Port { get; init; }
#endregion
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Validation;
using Microsoft.Extensions.Options;
#endregion
namespace Lumina.Presentation.Web.Common.Utilities;
/// <summary>
/// Extension methods for adding configuration related options services to the DI container via <see cref="OptionsBuilder{TOptions}"/>.
/// </summary>
public static class OptionsBuilderFluentValidationUtilities
{
#region ================================================================== METHODS ===================================================================================
/// <summary>
/// Extension method to add fluent validation to the options validation pipeline.
/// </summary>
/// <typeparam name="TOptions">The type of options being validated.</typeparam>
/// <param name="optionsBuilder">The options builder to add the validation to.</param>
/// <remarks>
/// This method allows validating options of type <typeparamref name="TOptions"/> using a FluentValidation validator registered in the DI container.
/// </remarks>
/// <returns>The same <see cref="OptionsBuilder{TOptions}"/> instance, to allow for chaining.</returns>
public static OptionsBuilder<TOptions> ValidateFluently<TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class
{
// register a singleton instance of IValidateOptions<TOptions> using FluentValidation
optionsBuilder.Services.AddSingleton<IValidateOptions<TOptions>>(
serviceProvider => new FluentValidationOptions<TOptions>(optionsBuilder.Name, serviceProvider.GetRequiredService<IValidator<TOptions>>()));
return optionsBuilder;
}
#endregion
}
@@ -0,0 +1,68 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Microsoft.Extensions.Options;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Provides options for fluent validation of a specific options type.
/// </summary>
/// <typeparam name="TOptions">The type of options being validated</typeparam>
public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> where TOptions : class
{
#region ================================================================== FIELD MEMBERS ================================================================================
private readonly IValidator<TOptions> _validator;
#endregion
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets the name of the options being validated.
/// </summary>
public string? Name { get; }
#endregion
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="FluentValidationOptions{TOptions}"/> class.
/// </summary>
/// <param name="name">The name of the options being validated. This can be <see langword="null"/>.</param>
/// <param name="validator">The validator instance used to validate the options.</param>
public FluentValidationOptions(string? name, IValidator<TOptions> validator)
{
Name = name;
_validator = validator;
}
#endregion
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Validates the specified <paramref name="options"/>.
/// </summary>
/// <param name="name">The name of the options instance being validated.</param>
/// <param name="options">The options instance to validate.</param>
/// <returns>A <see cref="ValidateOptionsResult"/> that indicates whether the validation was successful or not.</returns>
public ValidateOptionsResult Validate(string? name, TOptions options)
{
// check if the name of the options is specified and matches the provided one
if (Name is not null && Name != name)
return ValidateOptionsResult.Skip;
ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null
var validationResult = _validator.Validate(options); // validate the options using the validator
// return a response based on the validation result
if (validationResult.IsValid)
return ValidateOptionsResult.Success;
// if the validation fails, collect the error messages
// TODO: add translation support for the error messages
var errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'")
.ToArray();
// and return them with a failure result
return ValidateOptionsResult.Fail(errors);
}
#endregion
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Models.Configuration;
#endregion
namespace Lumina.Presentation.Web.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the ServerConfiguration application configuration settings section.
/// </summary>
public class ServerConfigurationModelValidator : AbstractValidator<ServerConfigurationModel>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="ServerConfigurationModelValidator"/> class.
/// </summary>
public ServerConfigurationModelValidator()
{
RuleFor(x => x.BaseAddress).NotEmpty().WithMessage("Base address cannot be empty!");
RuleFor(x => x.Port).InclusiveBetween((ushort)0, (ushort)65535).WithMessage("Port number must be between 0 and 65535!");
}
#endregion
}
@@ -0,0 +1,6 @@
{
"ServerConfiguration": {
"BaseAddress": "https://localhost",
"Port": 7057
}
}