Adds strongly typed IOptions<T> binding, with Fluent Validation and shared appsettings

- Adds strongly typed binding for IOptions<T> to map configuration sections from appsettings.json.
- Integrates FluentValidation for validating bound properties.
- Introduces appsettings.shared.json for shared configurations across applications.
Updates application-specific appsettings.json to focus on individual settings.
This commit is contained in:
BinaryAlley committed 2024-08-25 16:59:19 +03:00
1 parent b9dcb831e9
commit 433f0c2ad5
17 files changed
+383 -7

No files matched your search

@@ -19,7 +19,7 @@ public static class ApplicationLayerServices
/// Registers the services of the Application layer into the dependency injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <returns>The service collection with the added services.</returns>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
{
// register Mediator
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using System.Reflection;
using FluentValidation;
using Microsoft.Extensions.DependencyInjection;
#endregion
namespace Lumina.Infrastructure.Common.DependencyInjection;
/// <summary>
/// Contains all services of the Infrastructure layer.
/// </summary>
public static class InfrastructureLayerServices
{
#region ===================================================================== METHODS ===================================================================================
/// <summary>
/// Extension method for adding the Infrastructure layer services to the DI container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddInfrastructureLayerServices(this IServiceCollection services)
{
// scan the current assembly for validators and add them to the DI container
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton);
return services;
}
#endregion
}
@@ -0,0 +1,48 @@
#region ========================================================================= USING =====================================================================================
using System.Reflection;
using Lumina.Infrastructure.Common.Models.Configuration;
using Lumina.Infrastructure.Common.Utilities;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
#endregion
namespace Lumina.Infrastructure.Common.DependencyInjection;
/// <summary>
/// Class containing the shared configuration bindings of the application.
/// </summary>
public static class SharedConfiguration
{
#region ================================================================== METHODS ===================================================================================
/// <summary>
/// Extension method for registering the shared configuration to the DI container.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the configuration to.</param>
/// <param name="configuration">The configuration manager to use for the configuration.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
/// <exception cref="DirectoryNotFoundException">Thrown when the base path where the configuration files should be located, does not exist.</exception>
public static IServiceCollection BindSharedConfiguration(this IServiceCollection services, IConfigurationManager configuration)
{
var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(basePath))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
configuration.SetBasePath(basePath);
configuration.AddJsonFile("appsettings.shared.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.shared.Development.json", optional: true, reloadOnChange: true);
configuration.AddEnvironmentVariables(); // environment variables should override the configuration files
// bind the common settings section
services.AddOptions<CommonSettingsModel>()
.Bind(configuration.GetRequiredSection(CommonSettingsModel.SectionName))
.ValidateFluently()
.ValidateOnStart();
// bind the database connection string section
services.AddOptions<DatabaseSettingsModel>()
.Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SectionName))
.ValidateFluently()
.ValidateOnStart();
return services;
}
#endregion
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
#endregion
namespace Lumina.Infrastructure.Common.Errors;
/// <summary>
/// Application configuration error types.
/// </summary>
public static partial class Errors
{
public static class Configuration
{
#region ==================================================================== PROPERTIES =================================================================================
public static Error ApplicationThemeCannotBeEmpty => Error.Validation(nameof(ApplicationThemeCannotBeEmpty));
public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(nameof(DatabaseConnectionStringCannotBeEmpty));
#endregion
}
}
@@ -0,0 +1,18 @@
namespace Lumina.Infrastructure.Common.Models.Configuration;
/// <summary>
/// Model for deserializing shared application configuration settings.
/// </summary>
public class CommonSettingsModel
{
#region ================================================================== FIELD MEMBERS ================================================================================
public const string SectionName = "CommonSettings";
#endregion
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets or sets the theme of the application.
/// </summary>
public required string Theme { get; init; }
#endregion
}
@@ -0,0 +1,18 @@
namespace Lumina.Infrastructure.Common.Models.Configuration;
/// <summary>
/// Model for deserializing database configuration settings.
/// </summary>
public class DatabaseSettingsModel
{
#region ================================================================== FIELD MEMBERS ================================================================================
public const string SectionName = "ConnectionStrings";
#endregion
#region ==================================================================== PROPERTIES =================================================================================
/// <summary>
/// Gets or sets the connection string to the database.
/// </summary>
public required string DefaultConnection { get; init; }
#endregion
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Infrastructure.Common.Validation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
#endregion
namespace Lumina.Infrastructure.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.Infrastructure.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,22 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Infrastructure.Common.Models.Configuration;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the CommonSettings application configuration settings section.
/// </summary>
public class CommonSettingsModelValidator : AbstractValidator<CommonSettingsModel>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="CommonSettingsModelValidator"/> class.
/// </summary>
public CommonSettingsModelValidator()
{
RuleFor(x => x.Theme).NotEmpty().WithMessage(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty.Code);
}
#endregion
}
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Infrastructure.Common.Models.Configuration;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the ConnectionStrings application configuration settings section.
/// </summary>
public class DatabaseSettingsModelValidator : AbstractValidator<DatabaseSettingsModel>
{
#region ====================================================================== CTOR =====================================================================================
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseSettingsModelValidator"/> class.
/// </summary>
public DatabaseSettingsModelValidator()
{
RuleFor(x => x.DefaultConnection).NotEmpty().WithMessage(Errors.Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Code);
}
#endregion
}
@@ -7,6 +7,25 @@
<BaseOutputPath>..\..\bin\</BaseOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="11.9.2" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.shared.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.shared.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DependentUpon>appsettings.shared.json</DependentUpon>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
</ItemGroup>
@@ -0,0 +1,21 @@
{
"CommonSettings": {
"Theme": "LuminaDark"
},
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=Lumina;User Id=sa;Password=Password123;"
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.EntityFrameworkCore.Database.Command": "Debug"
}
},
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
]
}
}
@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using System.Reflection;
#endregion
namespace Lumina.Presentation.Api.Common.DependencyInjection;
/// <summary>
/// Class containing the configuration bindings of the Presentation API layer.
/// </summary>
internal static class PresentationApiLayerConfiguration
{
#region ================================================================== METHODS ===================================================================================
/// <summary>
/// Extension method for adding the Presentation API layer configuration to the DI container.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the configuration to.</param>
/// <param name="configuration">The configuration manager to use for the configuration.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
/// <exception cref="DirectoryNotFoundException">Thrown when the base path where the configuration files should be located, does not exist.</exception>
public static IServiceCollection BindPresentationApiLayerConfiguration(this IServiceCollection services, IConfigurationManager configuration)
{
var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!Directory.Exists(basePath))
throw new DirectoryNotFoundException($"The base path '{basePath}' does not exist.");
configuration.SetBasePath(basePath);
configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
configuration.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true);
return services;
}
#endregion
}
@@ -21,7 +21,7 @@ public static class PresentationApiLayerServices
/// Registers the services of the Presentation API layer into the dependency injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <returns>The service collection with the added services.</returns>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
{
// add services to the container
@@ -20,6 +20,16 @@
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<DependentUpon>appsettings.shared.json</DependentUpon>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Lumina.Application\Lumina.Application.csproj" />
+5
View File
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Common.DependencyInjection;
using Lumina.Application.Common.DependencyInjection;
using Lumina.Infrastructure.Common.DependencyInjection;
#endregion
namespace Lumina.Presentation.Api;
@@ -19,8 +20,12 @@ public class Program
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.BindSharedConfiguration(builder.Configuration);
builder.Services.BindPresentationApiLayerConfiguration(builder.Configuration);
builder.Services.AddApplicationLayerServices();
builder.Services.AddPresentationApiLayerServices();
builder.Services.AddInfrastructureLayerServices();
var app = builder.Build();
+17 -5
View File
@@ -1,9 +1,21 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
"Serilog": {
"WriteTo": [
{
"Name": "Debug"
},
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "Logs/lumina_api_.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
}
}
]
},
"AllowedHosts": "*"
}