diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md
new file mode 100644
index 00000000..68f31844
--- /dev/null
+++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0011.md
@@ -0,0 +1,134 @@
+# Architecture Decision Record (ADR): 0011 - Replace MediatR with Custom CQRS Abstractions
+
+## Status
+
+**Accepted** (2026-08-13)
+
+## Context
+
+The solution uses MediatR as a lightweight mediator to encapsulate command and query handling across the application layer. Following MediatR's shift to a commercial licensing model starting with .NET 8, continued use introduces an unacceptable external dependency on a paid third-party library for functionality that is entirely implementable in-house.
+
+Key constraints that shaped this decision:
+
+1. **Licensing Change**: MediatR became a commercial product for .NET 8+ projects, requiring a paid license for continued use in production systems.
+
+2. **Narrow Usage Scope**: MediatR is used for command and query dispatching, with a single pipeline behavior (automatic application validation) and no stream requests. Its notification publishing is used for domain event publishing, which is outside the scope of this ADR and is replaced separately (see ADR-0013).
+
+3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, the command and query dispatching provides no runtime value beyond a dispatch indirection that can be replaced by direct handler injection. It actually hurts performance by runtime dispatching of handlers via reflection.
+
+4. **Ownership and Transparency**: A custom implementation is fully owned, inspectable, and carries no transitive dependency risk or future licensing exposure.
+
+## Decision
+
+Replace MediatR with minimal, hand-written CQRS abstractions placed in `Lumina.Application.Common.CQRS`. Handlers are resolved directly via the .NET dependency injection container - no mediator object, no runtime reflection dispatch.
+
+### Core Abstractions
+
+```csharp
+// src/Lumina.Application/Common/CQRS/ICommand.cs
+
+///
+/// Marker interface for command types handled by .
+///
+public interface ICommand
+{
+}
+
+///
+/// Defines a contract for handling commands in the application layer.
+/// Commands represent operations that modify application state.
+///
+/// The type of command to handle.
+/// The type of result returned after handling the command.
+public interface ICommandHandler where TCommand : ICommand
+{
+ Task HandleAsync(TCommand command, CancellationToken cancellationToken = default);
+}
+```
+
+```csharp
+// src/Lumina.Application/Common/CQRS/IQuery.cs
+
+///
+/// Marker interface for query types handled by .
+///
+public interface IQuery
+{
+}
+
+///
+/// Defines a contract for handling queries in the application layer.
+/// Queries represent read operations that do not modify application state.
+///
+/// The type of query to handle.
+/// The type of result returned after handling the query.
+public interface IQueryHandler where TQuery : IQuery
+{
+ Task HandleAsync(TQuery query, CancellationToken cancellationToken = default);
+}
+```
+
+### Usage at Call Site
+
+Handlers are injected directly - no `ISender` or mediator intermediary:
+
+```csharp
+// Before (MediatR)
+internal sealed record GetConfiguredNismsQuery : IRequest>>;
+internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint
+{
+ private readonly ISender _sender;
+
+ public GetConfiguredNismsEndpoint(ISender sender)
+ {
+ _sender = sender;
+ }
+
+ public async Task>> ExecuteAsync(CancellationToken cancellationToken)
+ {
+ return await _sender.Send(new GetConfiguredNismsQuery(), cancellationToken).ConfigureAwait(false);
+ }
+}
+
+// After (custom abstraction)
+internal sealed record GetConfiguredNismsQuery : IQuery;
+internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint
+{
+ private readonly IQueryHandler>> _handler;
+
+ public GetConfiguredNismsEndpoint(IQueryHandler>> handler)
+ {
+ _handler = handler;
+ }
+
+ public async Task>> ExecuteAsync(CancellationToken cancellationToken)
+ {
+ return await _handler.HandleAsync(new GetConfiguredNismsQuery(), cancellationToken).ConfigureAwait(false);
+ }
+}
+```
+
+## Consequences
+
+### Positive Outcomes
+
+| Aspect | Benefit |
+|---|---|
+| Licensing | Eliminates commercial dependency and associated cost/compliance risk |
+| Simplicity | Removes an indirection layer unused beyond basic dispatch |
+| Transparency | Full ownership of dispatch logic; no hidden reflection or dynamic proxy behavior |
+| Testability | Handlers are tested directly via their interface, no mock mediator required |
+| DI Alignment | Leverages the existing .NET DI container idioms already present in the solution |
+| Performance | No runtime reflection, other than the startup registration of application use case handlers |
+
+### Risks and Mitigations
+
+| Risk | Mitigation Strategy |
+|---|---|
+| Loss of pipeline behavior support | Application validation will be performed manually, as an orchestration step |
+| Handler resolution errors surfacing at runtime | Covered by existing integration test suite that exercises the DI container on startup |
+| Increased boilerplate per feature | Marginal - one interface injection vs. `ISender`; offset by elimination of `IRequest` marker on every command/query |
+
+## Alternatives Considered
+
+No alternative libraries were evaluated. The sole driver for replacing MediatR was the licensing change, and the solution's usage is narrow enough that a first-party implementation is both sufficient and lower risk than adopting a different third-party mediator library.
diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md
new file mode 100644
index 00000000..27bf386e
--- /dev/null
+++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0012.md
@@ -0,0 +1,184 @@
+# Architecture Decision Record (ADR): 0012 - Replace FluentValidation with Custom Validation Abstractions
+
+## Status
+
+**Accepted** (2026-08-13)
+
+## Context
+
+The solution uses FluentValidation to validate commands and queries at the application boundary. A review of its usage across the codebase reveals a deliberately constrained subset of its feature set:
+
+1. **Narrow API Surface**: Only `RuleFor`, `Must`, `When`, and `WithMessage`-equivalent patterns are used. Advanced FluentValidation features - cascading rules, `RuleSets`, async validators, `SetValidator`, `Transform`, and the `AbstractValidator` inheritance tree beyond basic use - are absent throughout.
+
+2. **`Error`-typed Results**: The solution uses `ErrorOr` as its result type. FluentValidation returns `ValidationResult` / `ValidationFailure`, requiring a translation layer on every usage site to produce `Error` values, with some information loss in the process. A first-party validator can return `ErrorOr.Error` directly, with full metadata, eliminating that friction.
+
+3. **External Dependency Surface**: FluentValidation is a well-maintained library, but the danger of it going commercial, like other open source popular libraries in recent times, and the lack of usage of its advanced features mandates an in-house replacement.
+
+4. **Placement in SharedKernel**: Validation logic is cross-cutting and lives in `Lumina.Application.Common.Infrastructure.Validation`. Owning the abstraction entirely means the validation model stays aligned with the domain's `Error` type without any adapter.
+
+## Decision
+
+Replace FluentValidation with a minimal, first-party validation framework placed in `Lumina.Application.Common.Infrastructure.Validation`. The API mirrors FluentValidation's familiar fluent surface (`RuleFor`, `Must`, `When`, `WithError`) to minimize migration friction.
+
+### Core Abstractions
+
+```csharp
+// IValidator.cs - public contract consumed by application handlers
+public interface IValidator
+{
+ List Validate(TRequest instance);
+}
+
+// IValidationRule.cs - internal rule evaluation contract
+internal interface IValidationRule
+{
+ Error? Validate(TRequest instance);
+}
+
+// IRuleBuilder.cs - fluent configuration surface
+public interface IRuleBuilder
+{
+ IRuleBuilder Must(Func predicate);
+ IRuleBuilder When(Func condition);
+ IRuleBuilder WithError(Error error);
+}
+```
+
+### Base Validator
+
+```csharp
+// AbstractValidator.cs
+public abstract class AbstractValidator : IValidator
+{
+ private readonly List> _rules = [];
+
+ protected IRuleBuilder RuleFor(
+ Func propertySelector)
+ {
+ ValidationRule rule = new(propertySelector);
+ _rules.Add(rule);
+ return rule;
+ }
+
+ public List Validate(TRequest instance)
+ {
+ List errors = [];
+ foreach (IValidationRule rule in _rules)
+ {
+ Error? error = rule.Validate(instance);
+ if (error.HasValue)
+ errors.Add(error.Value);
+ }
+ return errors;
+ }
+}
+```
+
+### Concrete Rule Implementation
+
+```csharp
+// ValidationRule.cs - internal sealed, not exposed to consumers
+internal sealed class ValidationRule
+ : IValidationRule, IRuleBuilder
+{
+ private readonly Func _propertySelector;
+ private readonly List> _predicates = [];
+ private Error _error = Error.Validation();
+ private Func? _condition;
+
+ public ValidationRule(Func propertySelector)
+ => _propertySelector = propertySelector;
+
+ public IRuleBuilder Must(Func predicate)
+ {
+ _predicates.Add(predicate);
+ return this;
+ }
+
+ public IRuleBuilder When(Func condition)
+ {
+ _condition = condition;
+ return this;
+ }
+
+ public IRuleBuilder WithError(Error error)
+ {
+ _error = error;
+ return this;
+ }
+
+ public Error? Validate(TRequest instance)
+ {
+ if (_condition is not null && !_condition(instance))
+ return null;
+
+ TProperty value = _propertySelector(instance);
+ foreach (var predicate in _predicates)
+ if (!predicate(value))
+ return _error;
+
+ return null;
+ }
+}
+```
+
+### Built-in Extension Methods
+
+Common predicates are provided as extension methods on `IRuleBuilder` via `ValidatorUtilities`, placed in `Lumina.Application.Common.Utilities`:
+
+| Extension | Overloads | Behaviour |
+|---|---|---|
+| `NotEmpty()` | `string`, `List` | Fails if `null`, empty, or whitespace-only |
+| `GreaterThan(value)` | `int`, `int?`, `TimeSpan` | Fails if property ≤ value; nullable variant passes on `null` |
+| `IsInEnum()` | `TEnum`, `TEnum?` | Fails if value is not a defined enum member; nullable variant passes on `null` |
+
+### Usage Example
+
+```csharp
+internal sealed class CreateSensorCommandValidator : AbstractValidator
+{
+ public CreateSensorCommandValidator()
+ {
+ RuleFor(x => x.Name)
+ .NotEmpty()
+ .WithError(Errors.Sensor.NameRequired);
+
+ RuleFor(x => x.IntervalSeconds)
+ .GreaterThan(0)
+ .WithError(Errors.Sensor.InvalidInterval);
+
+ RuleFor(x => x.Type)
+ .IsInEnum()
+ .WithError(Errors.Sensor.InvalidType);
+
+ RuleFor(x => x.ThresholdOverride)
+ .GreaterThan(0)
+ .When(x => x.ThresholdOverride.HasValue)
+ .WithError(Errors.Sensor.InvalidThreshold);
+ }
+}
+```
+
+## Consequences
+
+### Positive Outcomes
+
+| Aspect | Benefit |
+|---|---|
+| `Error` Alignment | Validators return `List` directly - no `ValidationResult` → `Error` translation layer at call sites |
+| Dependency Reduction | Removes FluentValidation NuGet package and all transitive dependencies |
+| API Ownership | Full control over rule semantics, error shape, and future extension |
+| Familiar Surface | `RuleFor` / `Must` / `When` / `WithError` pattern is intentionally close to FluentValidation, minimising cognitive load during migration |
+| Encapsulation | `IValidationRule` and `ValidationRule` are `internal`; consumers only interact with `IValidator` and `IRuleBuilder` |
+
+### Risks and Mitigations
+
+| Risk | Mitigation Strategy |
+|---|---|
+| Missing built-in rules surfacing post-migration | Audit all existing FluentValidation rule usages before removal; add corresponding `ValidatorUtilities` extensions as needed |
+| Async validation not supported | No async validators exist, because this pertains to application use cases validation concerns (user input, etc), not business rules validations or invariants, which might require asynchronous or IO operations |
+| Loss of FluentValidation test helpers (`TestValidate`) | Replace with direct `ValidatorTestExtensions.TestValidate` calls in unit tests |
+
+## Alternatives Considered
+
+No alternative third-party validation libraries were evaluated, as this decision was not about replacing the FluentValidation libary with another library. The solution's validation usage is sufficiently narrow (property-level predicates, conditional execution, typed error results) that the cost of adopting and adapting another external library exceeds the cost of ownership of a purpose-built implementation aligned with the `ErrorOr` result model already in use.
diff --git a/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md
new file mode 100644
index 00000000..74e21de2
--- /dev/null
+++ b/docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0013.md
@@ -0,0 +1,76 @@
+# Architecture Decision Record (ADR): 0013 - Replace Mediator Domain Event Publishing with a Custom Implementation
+
+## Status
+
+**Accepted** (2026-08-13)
+
+## Context
+
+Domain event publishing, the mechanism that fires the `IDomainEvent` objects raised by aggregates to their handlers, depends on the Mediator library (`Mediator.Abstractions` and `Mediator.SourceGenerator`).
+
+1. **Event contract**: `IDomainEvent` implements Mediator's `INotification` marker interface.
+
+2. **Handler registration**: Domain event handlers implements Mediator's `INotificationHandler` and are registered by the source-generated `AddMediator` call.
+
+3. **Publishing sites**: Mediator's `IPublisher` is used from `EventualConsistencyMiddleware` (queued events, published after the transaction commits), from `MediaLibraryScanningService` (scan start events), and from the scan jobs and `ScanFailurePublisher` (progress and failure events).
+
+The remaining publish half carries the same third-party dependency and source-generated registration that ADR-0011 removed from the dispatch half.
+
+## Decision
+
+Replace Mediator's notification publishing with a first-party domain event publisher.
+
+### New Abstractions (in `Lumina.Domain.Common.Events`)
+
+- `IDomainEvent` no longer inherits `INotification`.
+- `IDomainEventPublisher` exposes `ValueTask PublishAsync(IDomainEvent domainEvent, CancellationToken cancellationToken = default)`.
+- `IDomainEventHandler` exposes `ValueTask HandleAsync(TDomainEvent domainEvent, CancellationToken cancellationToken)`. The type parameter is invariant so handlers stay mockable by dynamic proxy libraries.
+
+### Publisher Implementation (`DomainEventPublisher` in Infrastructure)
+
+- Scoped, resolving handlers for the event's runtime type from the DI container.
+- Dispatches through a compiled delegate cached per event type in a static `ConcurrentDictionary`, built once via `MakeGenericMethod` over a generic dispatch helper. Handlers run sequentially in registration order, exceptions propagate, and events without handlers are no-ops.
+- Registered next to the existing `IDomainEventsQueue`.
+
+### Registration (Application DI)
+
+The existing assembly scan that registers `ICommandHandler<>`, `IQueryHandler<>`, and `IValidator<>` now also registers `IDomainEventHandler<>` as scoped, replacing the source-generated `AddMediator`.
+
+### Consistency Guarantees Preserved
+
+- Commit-before-publish ordering in `EventualConsistencyMiddleware` is unchanged (see ADR-0002).
+- Re-entrant publishing (a handler publishing another event) is safe: each publish resolves handlers fresh from the scoped provider.
+- Jobs publish from their own scopes, so handlers receive a fresh unit of work and `DbContext`.
+
+## Consequences
+
+### Positive Outcomes
+
+| Aspect | Benefit |
+|---|---|
+| Dependency reduction | Removes `Mediator.Abstractions` and `Mediator.SourceGenerator` from the entire solution |
+| Transparency | Dispatch logic is fully owned and inspectable; no generated code |
+| Consistency | Domain event handlers join the same explicit registration scan as the CQRS handlers |
+| Single event contract | `IDomainEvent` remains the sole contract until a real cross-bounded-context consumer exists |
+
+### Risks and Mitigations
+
+| Risk | Mitigation Strategy |
+|---|---|
+| Handler resolution failures surface at runtime | Existing integration test suite exercises the DI container on startup |
+| Reflection-based dispatch per event type | Compiled delegate cache makes dispatch cheap after the first publish of each type |
+| Dynamic proxy cannot proxy generic interfaces | `IDomainEventHandler` is deliberately invariant so handlers remain mockable in unit tests |
+
+## Alternatives Considered
+
+### 1. Domain versus Integration Event Split
+
+Introduce `IIntegrationEvent` now, with a durable outbox, for inter-bounded-context propagation.
+
+**Rejected**: there are no cross-bounded-context consumers today - every event lives in the `LibraryManagementBoundedContext` and is handled in-process. The outbox machinery (durability, retries, idempotency) is speculative until the first real consumer appears, and forcing every existing event into one of two buckets would produce classification with no basis. The seam is documented on `IDomainEvent` itself so the split stays cheap to introduce later.
+
+### 2. Keeping Mediator for Publishing
+
+Keep the Mediator library for the domain event publishing half.
+
+**Rejected**: for the same reason ADR-0011 rejected it for command and query dispatching - an external dependency, with source-generated registration, for functionality that is fully implementable in-house.
diff --git a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs b/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs
deleted file mode 100644
index de644cc6..00000000
--- a/src/Lumina.Application/Common/Behaviors/ValidationBehavior.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using FluentValidation;
-using Mediator;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-#endregion
-
-namespace Lumina.Application.Common.Behaviors;
-
-///
-/// Represents a validation behavior in the Mediator pipeline for handling requests and responses.
-///
-/// The type representing a request. It should implement .
-/// The type representing a response. It should implement interface.
-public class ValidationBehavior : IPipelineBehavior where TRequest : IRequest
- where TResponse : IErrorOr
-{
- private readonly IValidator? _validator;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The validator used in this behavior pipeline for the Mediator commands and queries.
- public ValidationBehavior(IValidator? validator = null)
- {
- _validator = validator;
- }
-
- ///
- /// Pipeline handler. Perform any additional behavior and await the delegate as necessary.
- ///
- /// Incoming request.
- /// Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler.
- /// Cancellation token that can be used to stop the execution.
- public async ValueTask Handle(TRequest request, MessageHandlerDelegate next, CancellationToken cancellationToken)
- {
- // if there is no validator, just invoke the handler
- if (_validator is null)
- return await next(request, cancellationToken).ConfigureAwait(false);
- // before the handler of the command is executed
- FluentValidation.Results.ValidationResult validationResult = await _validator.ValidateAsync(request, cancellationToken).ConfigureAwait(false);
- // if there are no validation errors, invoke the command handler
- if (validationResult.IsValid)
- return await next(request, cancellationToken).ConfigureAwait(false);
- // after the command handler is executed
- List errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage));
- // the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic
- // this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!)
- return (dynamic)errors;
- }
-}
diff --git a/src/Lumina.Application/Common/CQRS/ICommand.cs b/src/Lumina.Application/Common/CQRS/ICommand.cs
new file mode 100644
index 00000000..c74204dc
--- /dev/null
+++ b/src/Lumina.Application/Common/CQRS/ICommand.cs
@@ -0,0 +1,8 @@
+namespace Lumina.Application.Common.CQRS;
+
+///
+/// Marker interface for command types handled by .
+///
+public interface ICommand
+{
+}
diff --git a/src/Lumina.Application/Common/CQRS/ICommandHandler.cs b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs
new file mode 100644
index 00000000..19e0018d
--- /dev/null
+++ b/src/Lumina.Application/Common/CQRS/ICommandHandler.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.CQRS;
+
+///
+/// Defines a contract for handling commands in the application layer.
+/// Commands represent operations that modify application state.
+///
+/// The type of command to handle.
+/// The type of result returned after handling the command.
+public interface ICommandHandler where TCommand : ICommand
+{
+ ///
+ /// Handles the specified command and returns a result.
+ ///
+ /// The command to handle.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation, containing the result of the command execution.
+ Task HandleAsync(TCommand command, CancellationToken cancellationToken = default);
+}
diff --git a/src/Lumina.Application/Common/CQRS/IQuery.cs b/src/Lumina.Application/Common/CQRS/IQuery.cs
new file mode 100644
index 00000000..dd2f42ed
--- /dev/null
+++ b/src/Lumina.Application/Common/CQRS/IQuery.cs
@@ -0,0 +1,8 @@
+namespace Lumina.Application.Common.CQRS;
+
+///
+/// Marker interface for query types handled by .
+///
+public interface IQuery
+{
+}
diff --git a/src/Lumina.Application/Common/CQRS/IQueryHandler.cs b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs
new file mode 100644
index 00000000..8b5fadde
--- /dev/null
+++ b/src/Lumina.Application/Common/CQRS/IQueryHandler.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Application.Common.CQRS;
+
+///
+/// Defines a contract for handling queries in the application layer.
+/// Queries represent read-only operations that retrieve data without modifying application state.
+///
+/// The type of query to handle.
+/// The type of result returned after handling the query.
+public interface IQueryHandler where TQuery : IQuery
+{
+ ///
+ /// Handles the specified query and returns a result.
+ ///
+ /// The query to handle.
+ /// Token to monitor for cancellation requests.
+ /// A task that represents the asynchronous operation, containing the result of the query execution.
+ Task HandleAsync(TQuery query, CancellationToken cancellationToken = default);
+}
diff --git a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
index 905573aa..229555a5 100644
--- a/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
+++ b/src/Lumina.Application/Common/DependencyInjection/ApplicationLayerServices.cs
@@ -1,9 +1,11 @@
#region ========================================================================= USING =====================================================================================
-using FluentValidation;
-using Lumina.Application.Common.Behaviors;
-using Mediator;
+using Lumina.Domain.Common.Events;
using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Reflection;
#endregion
namespace Lumina.Application.Common.DependencyInjection;
@@ -21,17 +23,33 @@ public static class ApplicationLayerServices
/// The updated .
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
{
- // register Mediator
- services.AddMediator(options =>
+ Type[] handlerContractTypes =
+ [
+ typeof(CQRS.ICommandHandler<,>),
+ typeof(CQRS.IQueryHandler<,>),
+ typeof(Infrastructure.Validation.IValidator<>),
+ typeof(IDomainEventHandler<>),
+ ];
+
+ IEnumerable concreteTypes = Assembly.GetExecutingAssembly()
+ .GetTypes()
+ .Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition);
+
+ var handlerRegistrations = concreteTypes
+ .SelectMany(implementation => implementation.GetInterfaces(),
+ (implementation, contract) => new { Contract = contract, Implementation = implementation })
+ .Where(registration => registration.Contract.IsGenericType && handlerContractTypes.Contains(registration.Contract.GetGenericTypeDefinition()));
+
+ foreach (var registration in handlerRegistrations)
{
- options.ServiceLifetime = ServiceLifetime.Scoped;
- });
+ if (services.Any(service => service.ServiceType == registration.Contract))
+ continue;
- // register the validation behavior
- services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
-
- // register fluent validators
- services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
+ if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
+ services.AddSingleton(registration.Contract, registration.Implementation);
+ else
+ services.AddScoped(registration.Contract, registration.Implementation);
+ }
return services;
}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs
new file mode 100644
index 00000000..cb40c867
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/AbstractValidator.cs
@@ -0,0 +1,57 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Base class for creating validators for commands and queries.
+///
+/// The type of the request (command or query) to be validated.
+public abstract class AbstractValidator : IValidator
+{
+ private readonly List> _rules = [];
+
+ ///
+ /// Defines a validation rule for a specific property on the request being validated.
+ ///
+ /// The type of the property being validated.
+ /// A function that selects the property to validate from the request instance.
+ /// An instance to configure the rule fluently.
+ public IRuleBuilder RuleFor(Func propertySelector)
+ {
+ ValidationRule rule = new(propertySelector);
+ _rules.Add(rule);
+ return rule;
+ }
+
+ ///
+ /// Defines a validation rule that is evaluated against each item within a collection property on the request being validated.
+ ///
+ /// The type of the items in the collection being validated.
+ /// A function that selects the collection to validate from the request instance.
+ /// An instance to configure the per-item rule fluently.
+ public IRuleBuilder RuleForEach(Func?> collectionSelector)
+ {
+ ValidationRuleForEach rule = new(collectionSelector);
+ _rules.Add(rule);
+ return rule;
+ }
+
+ ///
+ /// Validates the specified request instance against all defined rules.
+ ///
+ /// The request instance to validate.
+ /// A list of validation errors. If the instance is valid, the list will be empty.
+ public List Validate(TRequest instance)
+ {
+ List errors = [];
+
+ foreach (IValidationRule rule in _rules)
+ errors.AddRange(rule.Validate(instance));
+
+ return errors;
+ }
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs
new file mode 100644
index 00000000..771dcf73
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/IRuleBuilder.cs
@@ -0,0 +1,49 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Provides a fluent API for building validation rules for commands and queries.
+///
+/// The type of the request (command or query) being validated.
+/// The type of the specific property on the request that the rule applies to.
+public interface IRuleBuilder
+{
+ ///
+ /// Specifies a condition that the property must satisfy to be considered valid.
+ ///
+ /// A function to test the property value.
+ /// The current instance for method chaining.
+ IRuleBuilder Must(Func predicate);
+
+ ///
+ /// Specifies a condition that both the request instance and the property value must satisfy to be considered valid.
+ ///
+ /// A function to test the request instance together with the property value.
+ /// The current instance for method chaining.
+ IRuleBuilder Must(Func predicate);
+
+ ///
+ /// Specifies a condition that must be met for the validation rule to be executed.
+ ///
+ /// A function evaluating the request instance.
+ /// The current instance for method chaining.
+ IRuleBuilder When(Func condition);
+
+ ///
+ /// Specifies a custom object to be returned when the validation fails.
+ ///
+ /// The specific error to return upon failure.
+ /// The current instance for method chaining.
+ IRuleBuilder WithError(Error error);
+
+ ///
+ /// Defines nested validation rules for the complex property being validated.
+ ///
+ /// An action used to configure the inline validator for the property.
+ /// The current instance for method chaining.
+ IRuleBuilder ChildRules(Action> configure);
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs
new file mode 100644
index 00000000..a914dfd2
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/IValidationRule.cs
@@ -0,0 +1,20 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Interface for triggering commands and queries validator evaluation.
+///
+/// The type of the request (command or query) being evaluated.
+internal interface IValidationRule
+{
+ ///
+ /// Evaluates the validation rule against the specified request instance.
+ ///
+ /// The request instance to validate.
+ /// The s produced by this rule; empty if the rule passes.
+ IEnumerable Validate(TRequest instance);
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs
new file mode 100644
index 00000000..59467cb7
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/IValidator.cs
@@ -0,0 +1,20 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Interface for validating requests of commands and queries.
+///
+/// The type of the request (command or query) to be validated.
+public interface IValidator
+{
+ ///
+ /// Validates the specified request instance against the defined rules.
+ ///
+ /// The request instance to validate.
+ /// A list of validation errors. If the instance is valid, the list will be empty.
+ List Validate(TRequest instance);
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/InlineValidator.cs b/src/Lumina.Application/Common/Infrastructure/Validation/InlineValidator.cs
new file mode 100644
index 00000000..0a58b385
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/InlineValidator.cs
@@ -0,0 +1,12 @@
+#region ========================================================================= USING =====================================================================================
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Concrete used to declare validation rules inline for nested complex properties.
+///
+/// The type of the request (command or query) to be validated.
+public class InlineValidator : AbstractValidator
+{
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs
new file mode 100644
index 00000000..fc07a557
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRule.cs
@@ -0,0 +1,156 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Defines a validation rule for commands and queries that evaluates a specific property of a request.
+///
+/// The type of the request (command or query) being validated.
+/// The type of the specific property on the request that the rule applies to.
+internal sealed class ValidationRule : IValidationRule, IRuleBuilder
+{
+ private readonly Func _propertySelector;
+
+ // Predicates and their errors are kept in two parallel lists (rather than a single list of tuples)
+ // so that Must() can append cheaply and WithError() can patch the *last* entry by index, without
+ // having to rebuild a composite struct each time.
+ private readonly List> _predicates = [];
+ private readonly List _predicateErrors = [];
+
+ // instance-aware predicates get their own separate pair of lists instead of being merged into the
+ // lists above, because they have a different delegate signature (TRequest, TProperty) vs (TProperty).
+ // Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape.
+ private readonly List> _instanceAwarePredicates = [];
+ private readonly List _instanceAwarePredicateErrors = [];
+
+ private Error currentError = Error.Validation();
+ private Func? condition;
+
+ // Tracks which list WithError() should patch, since it doesn't know on its own whether the
+ // most recent Must() call went to the plain-predicate list or the instance-aware list.
+ private bool lastAddedPredicateIsInstanceAware;
+
+ private AbstractValidator? _childValidator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// A function that extracts the property value from the request instance.
+ public ValidationRule(Func propertySelector)
+ {
+ _propertySelector = propertySelector;
+ }
+
+ ///
+ /// Adds a condition that the property must satisfy to be considered valid.
+ ///
+ /// A function to test the property value.
+ /// The current instance for method chaining.
+ public IRuleBuilder Must(Func predicate)
+ {
+ _predicates.Add(predicate);
+ // Every predicate is paired with whatever error is "current" at the time it's added, so that a
+ // subsequent WithError() call has something concrete to overwrite via index lookup.
+ _predicateErrors.Add(currentError);
+ lastAddedPredicateIsInstanceAware = false;
+ return this;
+ }
+
+ ///
+ /// Adds a condition that the request instance together with the property must satisfy to be considered valid.
+ ///
+ /// A function to test the request instance together with the property value.
+ /// The current instance for method chaining.
+ public IRuleBuilder Must(Func predicate)
+ {
+ // This overload exists for cross-field rules (e.g. "EndDate must be after StartDate") where
+ // the check can't be expressed from the property value alone and needs the whole request.
+ _instanceAwarePredicates.Add(predicate);
+ _instanceAwarePredicateErrors.Add(currentError);
+ lastAddedPredicateIsInstanceAware = true;
+ return this;
+ }
+
+ ///
+ /// Specifies a condition that must be met for the validation rule to be executed.
+ ///
+ /// A function evaluating the request instance.
+ /// The current instance for method chaining.
+ public IRuleBuilder When(Func condition)
+ {
+ this.condition = condition;
+ return this;
+ }
+
+ ///
+ /// Specifies a custom object to be returned when the validation fails.
+ ///
+ /// The specific error to return upon failure.
+ /// The current instance for method chaining.
+ public IRuleBuilder WithError(Error error)
+ {
+ // Callers might pass in an error created with the wrong factory (e.g. Error.NotFound()) by mistake.
+ // Rebuilding it as Error.Validation() here guarantees every error surfaced by this class is
+ // consistently typed as a validation error, regardless of what the caller supplied.
+ Error validationError = Error.Validation(description: error.Description);
+ currentError = validationError;
+
+ // WithError() is meant to apply to the predicate that was *just* added via Must(), not to all
+ // predicates registered so far. Since Must() can target either parallel-list pair, we use the
+ // flag set by the last Must() call to figure out which list's last slot to overwrite.
+ if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0)
+ _instanceAwarePredicateErrors[^1] = validationError;
+ else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
+ _predicateErrors[^1] = validationError;
+ return this;
+ }
+
+ ///
+ /// Defines nested validation rules for the complex property being validated.
+ ///
+ /// An action used to configure the inline validator for the property.
+ /// The current instance for method chaining.
+ public IRuleBuilder ChildRules(Action> configure)
+ {
+ // Lets a rule delegate to a fully separate validator for a complex nested object (e.g. validating
+ // an Address property's own fields) instead of forcing every nested check to be flattened into
+ // Must() predicates on this rule.
+ InlineValidator childValidator = new();
+ configure(childValidator);
+ _childValidator = childValidator;
+ return this;
+ }
+
+ ///
+ /// Evaluates all configured predicates against the specified request instance.
+ ///
+ /// The request instance to validate.
+ /// The of every predicate that fails; empty if the rule passes.
+ public IEnumerable Validate(TRequest instance)
+ {
+ // evaluate the condition first, if it returns false, skip validation entirely.
+ if (condition is not null && !condition(instance))
+ yield break;
+
+ TProperty value = _propertySelector(instance);
+
+ // Deliberately does NOT stop at the first failure: every failing predicate contributes its own error,
+ // so a caller sees the full set of problems for // this property in one pass instead of having to fix
+ // and resubmit one error at a time.
+ for (int index = 0; index < _predicates.Count; index++)
+ if (!_predicates[index](value))
+ yield return _predicateErrors[index];
+
+ for (int index = 0; index < _instanceAwarePredicates.Count; index++)
+ if (!_instanceAwarePredicates[index](instance, value))
+ yield return _instanceAwarePredicateErrors[index];
+
+ if (_childValidator is not null && value is not null)
+ foreach (Error childError in _childValidator.Validate(value))
+ yield return childError;
+ }
+}
diff --git a/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs
new file mode 100644
index 00000000..4a5e08cc
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/Validation/ValidationRuleForEach.cs
@@ -0,0 +1,132 @@
+#region ========================================================================= USING =====================================================================================
+using ErrorOr;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure.Validation;
+
+///
+/// Defines a validation rule for commands and queries that evaluates each item within a collection property of a request.
+///
+/// The type of the request (command or query) being validated.
+/// The type of the items in the collection that the rule applies to.
+internal sealed class ValidationRuleForEach : IValidationRule, IRuleBuilder
+{
+ private readonly Func?> _collectionSelector;
+ private readonly List> _predicates = [];
+ private readonly List _predicateErrors = [];
+ private readonly List> _instanceAwarePredicates = [];
+ private readonly List _instanceAwarePredicateErrors = [];
+ private Error currentError = Error.Validation();
+ private Func? condition;
+ private bool lastAddedPredicateIsInstanceAware;
+ private AbstractValidator? _childValidator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// A function that extracts the collection to iterate from the request instance.
+ public ValidationRuleForEach(Func?> collectionSelector)
+ {
+ _collectionSelector = collectionSelector;
+ }
+
+ ///
+ /// Adds a condition that each item in the collection must satisfy to be considered valid.
+ ///
+ /// A function to test each item value.
+ /// The current instance for method chaining.
+ public IRuleBuilder Must(Func predicate)
+ {
+ _predicates.Add(predicate);
+ _predicateErrors.Add(currentError);
+ lastAddedPredicateIsInstanceAware = false;
+ return this;
+ }
+
+ ///
+ /// Adds a condition that the request instance together with each item must satisfy to be considered valid.
+ ///
+ /// A function to test the request instance together with each item value.
+ /// The current instance for method chaining.
+ public IRuleBuilder Must(Func predicate)
+ {
+ _instanceAwarePredicates.Add(predicate);
+ _instanceAwarePredicateErrors.Add(currentError);
+ lastAddedPredicateIsInstanceAware = true;
+ return this;
+ }
+
+ ///
+ /// Specifies a condition that must be met for the validation rule to be executed.
+ ///
+ /// A function evaluating the request instance.
+ /// The current instance for method chaining.
+ public IRuleBuilder When(Func condition)
+ {
+ this.condition = condition;
+ return this;
+ }
+
+ ///
+ /// Specifies a custom object to be returned when the validation fails.
+ ///
+ /// The specific error to return upon failure.
+ /// The current instance for method chaining.
+ public IRuleBuilder WithError(Error error)
+ {
+ // validation rules always produce validation errors, regardless of the error type of the source error
+ Error validationError = Error.Validation(description: error.Description);
+ currentError = validationError;
+ if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0)
+ _instanceAwarePredicateErrors[^1] = validationError;
+ else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
+ _predicateErrors[^1] = validationError;
+ return this;
+ }
+
+ ///
+ /// Defines nested validation rules for each item of the collection being validated.
+ ///
+ /// An action used to configure the inline validator for each item.
+ /// The current instance for method chaining.
+ public IRuleBuilder ChildRules(Action> configure)
+ {
+ InlineValidator childValidator = new();
+ configure(childValidator);
+ _childValidator = childValidator;
+ return this;
+ }
+
+ ///
+ /// Evaluates all configured predicates against each item in the collection.
+ ///
+ /// The request instance to validate.
+ /// One per failing predicate, per item; empty if every item passes.
+ public IEnumerable Validate(TRequest instance)
+ {
+ // evaluate the condition first, if it returns false, skip validation entirely.
+ if (condition is not null && !condition(instance))
+ yield break;
+
+ IEnumerable? collection = _collectionSelector(instance);
+ if (collection is null)
+ yield break;
+
+ foreach (TItem item in collection)
+ {
+ for (int index = 0; index < _predicates.Count; index++)
+ if (!_predicates[index](item))
+ yield return _predicateErrors[index];
+
+ for (int index = 0; index < _instanceAwarePredicates.Count; index++)
+ if (!_instanceAwarePredicates[index](instance, item))
+ yield return _instanceAwarePredicateErrors[index];
+
+ if (_childValidator is not null && item is not null)
+ foreach (Error childError in _childValidator.Validate(item))
+ yield return childError;
+ }
+ }
+}
diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs
new file mode 100644
index 00000000..86912552
--- /dev/null
+++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs
@@ -0,0 +1,326 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using System;
+using System.Collections;
+using System.Text.RegularExpressions;
+#endregion
+
+namespace Lumina.Application.Common.Utilities;
+
+///
+/// Validator extension methods for the to define common validation rules.
+///
+public static class ValidatorUtilities
+{
+ ///
+ /// Defines a validation rule that ensures the integer property is greater than the specified value.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, int valueToCompare)
+ {
+ return ruleBuilder.Must(value => value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the nullable integer property is greater than the specified value.
+ ///
+ ///
+ /// If the property is , this rule passes (use to check for missing values).
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, int valueToCompare)
+ {
+ return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the decimal property is greater than the specified value.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, decimal valueToCompare)
+ {
+ return ruleBuilder.Must(value => value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the nullable decimal property is greater than the specified value.
+ ///
+ ///
+ /// If the property is , this rule passes (use to check for missing values).
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, decimal valueToCompare)
+ {
+ return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the time span property is greater than the specified value.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, TimeSpan valueToCompare)
+ {
+ return ruleBuilder.Must(value => value > valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the integer property is greater than or equal to the specified value.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than or equal to.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, int valueToCompare)
+ {
+ return ruleBuilder.Must(value => value >= valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the nullable integer property is greater than or equal to the specified value.
+ ///
+ ///
+ /// If the property is , this rule passes.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than or equal to.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, int valueToCompare)
+ {
+ return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the nullable decimal property is greater than or equal to the specified value.
+ ///
+ ///
+ /// If the property is , this rule passes.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The value that the property must be greater than or equal to.
+ /// The current instance for method chaining.
+ public static IRuleBuilder GreaterThanOrEqualTo(this IRuleBuilder ruleBuilder, decimal valueToCompare)
+ {
+ return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the property is not .
+ ///
+ ///
+ /// This rule checks reference/nullable-value nullness only. Combine with
+ /// to also reject empty values.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder NotNull(this IRuleBuilder ruleBuilder)
+ {
+ return ruleBuilder.Must(value => value is not null);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the property is not empty.
+ ///
+ ///
+ /// This rule is type-aware: a is checked for white-space only content, a
+ /// is checked against , and any is checked for having at least
+ /// one item. If the property is , this rule fails.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder NotEmpty(this IRuleBuilder ruleBuilder)
+ {
+ return ruleBuilder.Must(value => value switch
+ {
+ null => false,
+ string stringValue => stringValue.Trim().Length > 0,
+ Guid guidValue => guidValue != Guid.Empty,
+ IEnumerable enumerable => enumerable.GetEnumerator().MoveNext(),
+ _ => true
+ });
+ }
+
+ ///
+ /// Defines a validation rule that ensures the value is a defined member of the specified enumeration type.
+ ///
+ /// The type of the request being validated.
+ /// The type of the enumeration.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum
+ {
+ return ruleBuilder.Must(value => Enum.IsDefined(value));
+ }
+
+ ///
+ /// Defines a validation rule that ensures a nullable enum value is either or a defined member of the specified enumeration type.
+ ///
+ /// The type of the request being validated.
+ /// The type of the enumeration.
+ /// The rule builder instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder IsInEnum(this IRuleBuilder ruleBuilder) where TEnum : struct, Enum
+ {
+ return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value));
+ }
+
+ ///
+ /// Defines a validation rule that ensures the string property does not exceed the specified maximum length.
+ ///
+ ///
+ /// If the property is or not a string, this rule passes.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// The maximum allowed length of the property.
+ /// The current instance for method chaining.
+ public static IRuleBuilder MaximumLength(this IRuleBuilder ruleBuilder, int maximumLength)
+ {
+ return ruleBuilder.Must(value => value is not string stringValue || stringValue.Length <= maximumLength);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the string property is at least the specified minimum length.
+ ///
+ ///
+ /// If the property is or not a string, this rule fails.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// The minimum allowed length of the property.
+ /// The current instance for method chaining.
+ public static IRuleBuilder MinimumLength(this IRuleBuilder ruleBuilder, int minimumLength)
+ {
+ return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the string property has exactly the specified length.
+ ///
+ ///
+ /// If the property is or not a string, this rule fails.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// The exact allowed length of the property.
+ /// The current instance for method chaining.
+ public static IRuleBuilder Length(this IRuleBuilder ruleBuilder, int length)
+ {
+ return ruleBuilder.Must(value => value is string stringValue && stringValue.Length == length);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the string property length is within the specified inclusive range.
+ ///
+ ///
+ /// If the property is or not a string, this rule fails.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// The minimum allowed length of the property.
+ /// The maximum allowed length of the property.
+ /// The current instance for method chaining.
+ public static IRuleBuilder Length(this IRuleBuilder ruleBuilder, int minimumLength, int maximumLength)
+ {
+ return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength && stringValue.Length <= maximumLength);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the string property matches the specified regular expression pattern.
+ ///
+ ///
+ /// If the property is or not a string, this rule fails (use
+ /// to skip optional properties).
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// The regular expression pattern the property must match.
+ /// The current instance for method chaining.
+ public static IRuleBuilder Matches(this IRuleBuilder ruleBuilder, string regexPattern)
+ {
+ return ruleBuilder.Must(value => value is string stringValue && Regex.IsMatch(stringValue, regexPattern));
+ }
+
+ ///
+ /// Defines a validation rule that ensures the string property matches the regular expression pattern selected from the request instance.
+ ///
+ ///
+ /// If the property is or not a string, this rule fails.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// A function that selects the regular expression pattern to match against from the request instance.
+ /// The current instance for method chaining.
+ public static IRuleBuilder Matches(this IRuleBuilder ruleBuilder, Func regexPatternSelector)
+ {
+ return ruleBuilder.Must((instance, value) => value is string stringValue && Regex.IsMatch(stringValue, regexPatternSelector(instance)));
+ }
+
+ ///
+ /// Defines a validation rule that ensures the integer property is within the specified inclusive range.
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The minimum allowed value of the property.
+ /// The maximum allowed value of the property.
+ /// The current instance for method chaining.
+ public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, int minimumValue, int maximumValue)
+ {
+ return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue);
+ }
+
+ ///
+ /// Defines a validation rule that ensures the nullable integer property is within the specified inclusive range.
+ ///
+ ///
+ /// If the property is , this rule passes (use to check for missing values).
+ ///
+ /// The type of the request being validated.
+ /// The rule builder instance.
+ /// The minimum allowed value of the property.
+ /// The maximum allowed value of the property.
+ /// The current instance for method chaining.
+ public static IRuleBuilder InclusiveBetween(this IRuleBuilder ruleBuilder, int minimumValue, int maximumValue)
+ {
+ return ruleBuilder.Must(value => !value.HasValue || (value.Value >= minimumValue && value.Value <= maximumValue));
+ }
+
+ ///
+ /// Defines a validation rule that ensures the property is equal to another property of the request.
+ ///
+ /// The type of the request being validated.
+ /// The type of the property being validated.
+ /// The rule builder instance.
+ /// A function that selects the property the validated property must equal.
+ /// The current instance for method chaining.
+ public static IRuleBuilder Equal(this IRuleBuilder ruleBuilder, Func comparisonSelector)
+ {
+ return ruleBuilder.Must((instance, value) => Equals(value, comparisonSelector(instance)));
+ }
+}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs
index 93184771..3acbe0d2 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQuery.cs
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.Authorization;
-using Mediator;
-using System.Collections.Generic;
+using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer
///
/// Query for retrieving the list of authorization permissions.
///
-public record GetPermissionsQuery : IRequest>>;
+public record GetPermissionsQuery : IQuery;
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs
index 3b00e28f..c95dddb8 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Permissions/Queries/GetPermissions/GetPermissionsQueryHandler.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
@@ -8,7 +9,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
-using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -19,7 +19,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPer
///
/// Handler for the query to retrieve the list of authorization permissions.
///
-public class GetPermissionsQueryHandler : IRequestHandler>>
+public class GetPermissionsQueryHandler : IQueryHandler>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
@@ -41,12 +41,12 @@ public class GetPermissionsQueryHandler : IRequestHandler
/// Handles the query to retrieve the list of authorization permissions.
///
- /// The request to be handled.
+ /// The request to be handled.
/// Cancellation token that can be used to stop the execution.
///
/// An containing either a collection of , or an error message.
///
- public async ValueTask>> Handle(GetPermissionsQuery request, CancellationToken cancellationToken)
+ public async Task>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken)
{
// only admins can see the list of authorization permissions
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs
index bdbd33aa..840e75eb 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommand.cs
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -18,4 +16,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
public record AddRoleCommand(
string RoleName,
List Permissions
-) : IRequest>;
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs
index 74c13ceb..ecc324ac 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandHandler.cs
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -19,11 +21,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
///
/// Handler for the command to add an authorization role.
///
-public class AddRoleCommandHandler : IRequestHandler>
+public class AddRoleCommandHandler : ICommandHandler>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
@@ -31,11 +34,13 @@ public class AddRoleCommandHandler : IRequestHandlerInjected service for authorization related functionality.
/// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
- public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
+ /// Injected validator for application validation rules.
+ public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
+ _validator = validator;
}
///
@@ -46,8 +51,12 @@ public class AddRoleCommandHandler : IRequestHandler
/// An containing either a successfully created , or an error message.
///
- public async ValueTask> Handle(AddRoleCommand request, CancellationToken cancellationToken)
+ public async Task> HandleAsync(AddRoleCommand request, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(request);
+ if (validationResult.Count > 0)
+ return validationResult;
+
// only admins can create authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
@@ -59,13 +68,13 @@ public class AddRoleCommandHandler : IRequestHandler new RolePermissionEntity()
+ RolePermissions = [.. request.Permissions.Select(permissionId => new RolePermissionEntity()
{
PermissionId = permissionId,
Permission = null!,
Role = null!,
RoleId = default
- }).ToList()
+ })]
};
// save the new role in the repository
ErrorOr insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false);
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs
index a2b2f01f..ab5804db 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/AddRole/AddRoleCommandValidator.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
-using FluentValidation;
using Lumina.Application.Common.Errors;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
using System;
#endregion
@@ -17,14 +18,15 @@ public class AddRoleCommandValidator : AbstractValidator
public AddRoleCommandValidator()
{
RuleFor(x => x.RoleName)
- .NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description)
- .NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
+ .NotNull().WithError(Errors.Authorization.RoleNameCannotBeNull)
+ .NotEmpty().WithError(Errors.Authorization.RoleNameCannotBeEmpty);
RuleFor(x => x.Permissions)
- .NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description)
- .NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description);
+ .NotNull().WithError(Errors.Authorization.PermissionsListCannotBeNull)
+ .NotEmpty().WithError(Errors.Authorization.PermissionsListCannotBeEmpty);
+
RuleForEach(x => x.Permissions)
- .NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description)
- .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description);
+ .NotEmpty().WithError(Errors.Authorization.PermissionIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty).WithError(Errors.Authorization.PermissionIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs
index 9cccdad1..af1d3265 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommand.cs
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Mediator;
+using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -14,4 +13,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
[DebuggerDisplay("RoleId: {RoleId}")]
public record DeleteRoleCommand(
Guid RoleId
-) : IRequest>;
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs
index df10ee28..a4de4b25 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandHandler.cs
@@ -1,12 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.Authorization;
-using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -21,11 +22,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
///
/// Handler for the command to delete an authorization role.
///
-public class DeleteRoleCommandHandler : IRequestHandler>
+public class DeleteRoleCommandHandler : ICommandHandler>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
@@ -33,21 +35,27 @@ public class DeleteRoleCommandHandler : IRequestHandlerInjected service for authorization related functionality.
/// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
- public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
+ /// Injected validator for application validation rules.
+ public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
+ _validator = validator;
}
///
/// Handles the command to delete an authorization role.
///
- /// The request to be handled.
+ /// The request to be handled.
/// Cancellation token that can be used to stop the execution.
/// An representing either a successful operation, or an error.
- public async ValueTask> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
+ public async Task> HandleAsync(DeleteRoleCommand command, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
// only admins can delete authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
@@ -55,7 +63,7 @@ public class DeleteRoleCommandHandler : IRequestHandler();
- ErrorOr getExistingRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
+ ErrorOr getExistingRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
if (getExistingRoleResult.IsError)
return getExistingRoleResult.Errors;
else if (getExistingRoleResult.Value is null)
@@ -63,7 +71,7 @@ public class DeleteRoleCommandHandler : IRequestHandler deleteRoleResult = await roleRepository.DeleteByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
+ ErrorOr deleteRoleResult = await roleRepository.DeleteByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
if (deleteRoleResult.IsError)
return deleteRoleResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs
index a64205d5..8c5984d2 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/DeleteRole/DeleteRoleCommandValidator.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
-using FluentValidation;
using Lumina.Application.Common.Errors;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
using System;
#endregion
@@ -16,8 +17,8 @@ public class DeleteRoleCommandValidator : AbstractValidator
///
public DeleteRoleCommandValidator()
{
- RuleFor(x => x.RoleId)
- .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
- .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
+ RuleFor(command => command.RoleId)
+ .NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs
index 98ce2684..0b4fcd67 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommand.cs
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -20,4 +18,4 @@ public record UpdateRoleCommand(
Guid RoleId,
string RoleName,
List Permissions
-) : IRequest>;
+) : ICommand;
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs
index 11ebe913..5534b42b 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandHandler.cs
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -19,11 +21,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
///
/// Handler for the command to update an authorization role.
///
-public class UpdateRoleCommandHandler : IRequestHandler>
+public class UpdateRoleCommandHandler : ICommandHandler>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IAuthorizationService _authorizationService;
private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
@@ -31,23 +34,29 @@ public class UpdateRoleCommandHandler : IRequestHandlerInjected service for authorization related functionality.
/// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
- public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
+ /// Injected validator for application validation rules.
+ public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
_unitOfWork = unitOfWork;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
+ _validator = validator;
}
///
/// Handles the command to update an authorization role.
///
- /// The request to be handled.
+ /// The request to be handled.
/// Cancellation token that can be used to stop the execution.
///
/// An containing either a successfully updated , or an error message.
///
- public async ValueTask> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
+ public async Task> HandleAsync(UpdateRoleCommand command, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
// only admins can update authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
@@ -58,9 +67,9 @@ public class UpdateRoleCommandHandler : IRequestHandler new RolePermissionEntity()
+ Id = command.RoleId,
+ RoleName = command.RoleName,
+ RolePermissions = command.Permissions.Select(permissionId => new RolePermissionEntity()
{
PermissionId = permissionId,
Permission = null!,
@@ -74,7 +83,7 @@ public class UpdateRoleCommandHandler : IRequestHandler getRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
+ ErrorOr getRoleResult = await roleRepository.GetByIdAsync(command.RoleId, cancellationToken).ConfigureAwait(false);
if (getRoleResult.IsError)
return getRoleResult.Errors;
if (getRoleResult.Value is null)
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs
index 4672ed03..af0253da 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Commands/UpdateRole/UpdateRoleCommandValidator.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
-using FluentValidation;
using Lumina.Application.Common.Errors;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
using System;
#endregion
@@ -16,19 +17,20 @@ public class UpdateRoleCommandValidator : AbstractValidator
///
public UpdateRoleCommandValidator()
{
- RuleFor(x => x.RoleId)
- .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
- .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
+ RuleFor(command => command.RoleId)
+ .NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty);
- RuleFor(x => x.RoleName)
- .NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description)
- .NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
+ RuleFor(command => command.RoleName)
+ .NotNull().WithError(Errors.Authorization.RoleNameCannotBeNull)
+ .NotEmpty().WithError(Errors.Authorization.RoleNameCannotBeEmpty);
- RuleFor(x => x.Permissions)
- .NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description)
- .NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description);
- RuleForEach(x => x.Permissions)
- .NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description)
- .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description);
+ RuleFor(command => command.Permissions)
+ .NotNull().WithError(Errors.Authorization.PermissionsListCannotBeNull)
+ .NotEmpty().WithError(Errors.Authorization.PermissionsListCannotBeEmpty);
+
+ RuleForEach(command => command.Permissions)
+ .NotEmpty().WithError(Errors.Authorization.PermissionIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty).WithError(Errors.Authorization.PermissionIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs
index 6050dc46..38202928 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQuery.cs
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi
[DebuggerDisplay("RoleId: {RoleId}")]
public record GetRolePermissionsQuery(
Guid RoleId
-) : IRequest>;
+) : IQuery;
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
index 7305064c..c1735073 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryHandler.cs
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
-using Mediator;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -18,11 +20,12 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermi
///
/// Handler for the query to retrieve the list of authorization permissions for a role.
///
-public class GetRolePermissionsQueryHandler : IRequestHandler>
+public class GetRolePermissionsQueryHandler : IQueryHandler>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IRoleRepository _roleRepository;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
@@ -30,11 +33,13 @@ public class GetRolePermissionsQueryHandler : IRequestHandlerInjected service for authorization related functionality.
/// Injected service to retrieve the current user information.
/// Injected unit of work for interacting with the data access layer repositories.
- public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
+ /// Injected validator for application validation rules.
+ public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_roleRepository = unitOfWork.GetRepository();
+ _validator = validator;
}
///
@@ -45,8 +50,12 @@ public class GetRolePermissionsQueryHandler : IRequestHandler
/// An containing either a collection of , or an error message.
///
- public async ValueTask> Handle(GetRolePermissionsQuery request, CancellationToken cancellationToken)
+ public async Task> HandleAsync(GetRolePermissionsQuery request, CancellationToken cancellationToken)
{
+ List validationResult = _validator.Validate(request);
+ if (validationResult.Count > 0)
+ return validationResult;
+
// only admins can see the list of authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs
index 107b65d3..565cc7fb 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRolePermissions/GetRolePermissionsQueryValidator.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
-using FluentValidation;
using Lumina.Application.Common.Errors;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
using System;
#endregion
@@ -17,7 +18,7 @@ public class GetRolePermissionsQueryValidator : AbstractValidator x.RoleId)
- .NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
- .Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
+ .NotEmpty().WithError(Errors.Authorization.RoleIdCannotBeEmpty)
+ .Must(id => id != Guid.Empty).WithError(Errors.Authorization.RoleIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs
index 6a168b06..df96049a 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQuery.cs
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.Authorization;
-using Mediator;
-using System.Collections.Generic;
+using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
///
/// Query for retrieving the list of authorization roles.
///
-public record GetRolesQuery() : IRequest>>;
+public record GetRolesQuery() : IQuery;
diff --git a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs
index 405086ac..db716a4b 100644
--- a/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs
+++ b/src/Lumina.Application/Core/Admin/Authorization/Roles/Queries/GetRoles/GetRolesQueryHandler.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.UoW;
@@ -8,7 +9,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
-using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -19,7 +19,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
///
/// Handler for the query to retrieve the list of authorization roles.
///
-public class GetRolesQueryHandler : IRequestHandler>>
+public class GetRolesQueryHandler : IQueryHandler>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
@@ -41,12 +41,12 @@ public class GetRolesQueryHandler : IRequestHandler
/// Handles the query to retrieve the list of authorization roles.
///
- /// The request to be handled.
+ /// The request to be handled.
/// Cancellation token that can be used to stop the execution.
///
/// An containing either a collection of , or an error message.
///
- public async ValueTask>> Handle(GetRolesQuery request, CancellationToken cancellationToken)
+ public async Task>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken)
{
// only admins can see the list of authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs
index c4be3e4b..86da3e1c 100644
--- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs
+++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQuery.cs
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.FileSystemManagement.Directories;
-using Mediator;
-using System.Collections.Generic;
+using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
@@ -17,4 +14,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDi
public record GetDirectoriesQuery(
string? Path,
bool IncludeHiddenElements
-) : IRequest>>;
+) : IQuery;
diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs
index bfda1160..141362f8 100644
--- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs
+++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryHandler.cs
@@ -1,10 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
+using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
+using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
-using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -15,30 +16,37 @@ namespace Lumina.Application.Core.FileSystemManagement.Directories.Queries.GetDi
///
/// Handler for the query to get all directories.
///
-public class GetDirectoriesQueryHandler : IRequestHandler>>
+public class GetDirectoriesQueryHandler : IQueryHandler>>
{
private readonly IDirectoryService _directoryService;
+ private readonly IValidator _validator;
///
/// Initializes a new instance of the class.
///
/// Injected service for handling directories.
- public GetDirectoriesQueryHandler(IDirectoryService directoryService)
+ /// Injected validator for application validation rules.
+ public GetDirectoriesQueryHandler(IDirectoryService directoryService, IValidator validator)
{
_directoryService = directoryService;
+ _validator = validator;
}
///
/// Gets the list of directories at the specified path.
///
- /// The query containing the requested path.
+ /// The query containing the requested path.
/// Cancellation token that can be used to stop the execution.
///
/// An containing either a collection of , or an error message.
///
- public ValueTask>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
+ public Task>> HandleAsync(GetDirectoriesQuery query, CancellationToken cancellationToken)
{
- ErrorOr> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
- return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
+ List validationResult = _validator.Validate(query);
+ if (validationResult.Count > 0)
+ return Task.FromResult>>(validationResult);
+
+ ErrorOr> getSubdirectoriesResult = _directoryService.GetSubdirectories(query.Path!, query.IncludeHiddenElements);
+ return Task.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
}
}
diff --git a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs
index f7012600..601823c9 100644
--- a/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs
+++ b/src/Lumina.Application/Core/FileSystemManagement/Directories/Queries/GetDirectories/GetDirectoriesQueryValidator.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
-using FluentValidation;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -15,6 +16,8 @@ public class GetDirectoriesQueryValidator : AbstractValidator
public GetDirectoriesQueryValidator()
{
- RuleFor(x => x.Path).NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description);
+ RuleFor(query => query.Path)
+ .NotEmpty()
+ .WithError(Errors.FileSystemManagement.PathCannotBeEmpty);
}
-}
\ No newline at end of file
+}
diff --git a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs
index 74b2c0b0..a9b8cd0a 100644
--- a/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs
+++ b/src/Lumina.Application/Core/FileSystemManagement/Drives/Queries/GetDrives/GetDrivesQuery.cs
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
-using ErrorOr;
-using Lumina.Contracts.Responses.FileSystemManagement.Common;
-using Mediator;
-using System.Collections.Generic;
+using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
///