diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs index c83f12ac..2f7fc3a7 100644 --- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs +++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs @@ -19,7 +19,7 @@ public static class ApplicationLayerServices /// Registers the services of the Application layer into the dependency injection container. /// /// The service collection to add the services to. - /// The service collection with the added services. + /// The updated . public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services) { // register Mediator diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs new file mode 100644 index 00000000..75aa6fc8 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using System.Reflection; +using FluentValidation; +using Microsoft.Extensions.DependencyInjection; +#endregion + +namespace Lumina.Infrastructure.Common.DependencyInjection; + +/// +/// Contains all services of the Infrastructure layer. +/// +public static class InfrastructureLayerServices +{ + #region ===================================================================== METHODS =================================================================================== + /// + /// Extension method for adding the Infrastructure layer services to the DI container. + /// + /// The service collection to add the services to. + /// The updated . + 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 +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs new file mode 100644 index 00000000..45267055 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -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; + +/// +/// Class containing the shared configuration bindings of the application. +/// +public static class SharedConfiguration +{ + #region ================================================================== METHODS =================================================================================== + /// + /// Extension method for registering the shared configuration to the DI container. + /// + /// The to add the configuration to. + /// The configuration manager to use for the configuration. + /// The updated . + /// Thrown when the base path where the configuration files should be located, does not exist. + 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() + .Bind(configuration.GetRequiredSection(CommonSettingsModel.SectionName)) + .ValidateFluently() + .ValidateOnStart(); + + // bind the database connection string section + services.AddOptions() + .Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SectionName)) + .ValidateFluently() + .ValidateOnStart(); + return services; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs new file mode 100644 index 00000000..948a2ee3 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using ErrorOr; +#endregion + +namespace Lumina.Infrastructure.Common.Errors; + +/// +/// Application configuration error types. +/// +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 + } +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/CommonSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/CommonSettingsModel.cs new file mode 100644 index 00000000..c19ec636 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/Configuration/CommonSettingsModel.cs @@ -0,0 +1,18 @@ +namespace Lumina.Infrastructure.Common.Models.Configuration; + +/// +/// Model for deserializing shared application configuration settings. +/// +public class CommonSettingsModel +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + public const string SectionName = "CommonSettings"; + #endregion + + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets or sets the theme of the application. + /// + public required string Theme { get; init; } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/DatabaseSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/DatabaseSettingsModel.cs new file mode 100644 index 00000000..8fe6022d --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Models/Configuration/DatabaseSettingsModel.cs @@ -0,0 +1,18 @@ +namespace Lumina.Infrastructure.Common.Models.Configuration; + +/// +/// Model for deserializing database configuration settings. +/// +public class DatabaseSettingsModel +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + public const string SectionName = "ConnectionStrings"; + #endregion + + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets or sets the connection string to the database. + /// + public required string DefaultConnection { get; init; } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs b/src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs new file mode 100644 index 00000000..5c7a8570 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Utilities/OptionsBuilderFluentValidationUtilities.cs @@ -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; + +/// +/// Extension methods for adding configuration related options services to the DI container via . +/// +public static class OptionsBuilderFluentValidationUtilities +{ + #region ================================================================== METHODS =================================================================================== + /// + /// Extension method to add fluent validation to the options validation pipeline. + /// + /// The type of options being validated. + /// The options builder to add the validation to. + /// + /// This method allows validating options of type using a FluentValidation validator registered in the DI container. + /// + /// The same instance, to allow for chaining. + public static OptionsBuilder ValidateFluently(this OptionsBuilder optionsBuilder) where TOptions : class + { + // register a singleton instance of IValidateOptions using FluentValidation + optionsBuilder.Services.AddSingleton>( + serviceProvider => new FluentValidationOptions(optionsBuilder.Name, serviceProvider.GetRequiredService>())); + return optionsBuilder; + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs b/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs new file mode 100644 index 00000000..913c38f0 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validation/FluentValidationOptions.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Microsoft.Extensions.Options; +#endregion + +namespace Lumina.Infrastructure.Common.Validation; + +/// +/// Provides options for fluent validation of a specific options type. +/// +/// The type of options being validated +public class FluentValidationOptions : IValidateOptions where TOptions : class +{ + #region ================================================================== FIELD MEMBERS ================================================================================ + private readonly IValidator _validator; + #endregion + + #region ==================================================================== PROPERTIES ================================================================================= + /// + /// Gets the name of the options being validated. + /// + public string? Name { get; } + #endregion + + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + /// The name of the options being validated. This can be . + /// The validator instance used to validate the options. + public FluentValidationOptions(string? name, IValidator validator) + { + Name = name; + _validator = validator; + } + #endregion + + #region ===================================================================== METHODS =================================================================================== + /// + /// Validates the specified . + /// + /// The name of the options instance being validated. + /// The options instance to validate. + /// A that indicates whether the validation was successful or not. + 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 +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/Validators/CommonSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/CommonSettingsModelValidator.cs new file mode 100644 index 00000000..0dbf7a74 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/CommonSettingsModelValidator.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Infrastructure.Common.Models.Configuration; +#endregion + +namespace Lumina.Infrastructure.Common.Validators; + +/// +/// Validates the needed validation rules for the CommonSettings application configuration settings section. +/// +public class CommonSettingsModelValidator : AbstractValidator +{ + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public CommonSettingsModelValidator() + { + RuleFor(x => x.Theme).NotEmpty().WithMessage(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty.Code); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsModelValidator.cs new file mode 100644 index 00000000..74be0d32 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Validators/DatabaseSettingsModelValidator.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using FluentValidation; +using Lumina.Infrastructure.Common.Models.Configuration; +#endregion + +namespace Lumina.Infrastructure.Common.Validators; + +/// +/// Validates the needed validation rules for the ConnectionStrings application configuration settings section. +/// +public class DatabaseSettingsModelValidator : AbstractValidator +{ + #region ====================================================================== CTOR ===================================================================================== + /// + /// Initializes a new instance of the class. + /// + public DatabaseSettingsModelValidator() + { + RuleFor(x => x.DefaultConnection).NotEmpty().WithMessage(Errors.Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Code); + } + #endregion +} \ No newline at end of file diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 1eadaafa..ba592b0c 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -7,6 +7,25 @@ ..\..\bin\ + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + appsettings.shared.json + + + diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json new file mode 100644 index 00000000..64b489af --- /dev/null +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -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" + ] + } +} \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs new file mode 100644 index 00000000..b662c601 --- /dev/null +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerConfiguration.cs @@ -0,0 +1,33 @@ +#region ========================================================================= USING ===================================================================================== +using System.Reflection; +#endregion + +namespace Lumina.Presentation.Api.Common.DependencyInjection; + +/// +/// Class containing the configuration bindings of the Presentation API layer. +/// +internal static class PresentationApiLayerConfiguration +{ + #region ================================================================== METHODS =================================================================================== + /// + /// Extension method for adding the Presentation API layer configuration to the DI container. + /// + /// The to add the configuration to. + /// The configuration manager to use for the configuration. + /// The updated . + /// Thrown when the base path where the configuration files should be located, does not exist. + 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 +} \ No newline at end of file diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index e728c0ff..b7c8f07b 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -21,7 +21,7 @@ public static class PresentationApiLayerServices /// Registers the services of the Presentation API layer into the dependency injection container. /// /// The service collection to add the services to. - /// The service collection with the added services. + /// The updated . public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services) { // add services to the container diff --git a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj index a8b6a0c1..064a3a6d 100644 --- a/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj +++ b/src/Lumina.Presentation.Api/Lumina.Presentation.Api.csproj @@ -20,6 +20,16 @@ + + + + PreserveNewest + + + PreserveNewest + appsettings.shared.json + + diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 1b673202..314ca370 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -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(); diff --git a/src/Lumina.Presentation.Api/appsettings.json b/src/Lumina.Presentation.Api/appsettings.json index 4d566948..f7db36a3 100644 --- a/src/Lumina.Presentation.Api/appsettings.json +++ b/src/Lumina.Presentation.Api/appsettings.json @@ -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": "*" }