mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 22:11:10 +00:00
Defines base implementation for mediatr and fluentvalidation with samples
This commit is contained in:
1 parent
76db0c1597
commit
9a5c7473f9
33 files changed
+1123
-131
No files matched your search
+134
@@ -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 exclusively for command and query dispatching - only one pipeline behavior (automatic application validation) and no notification publishing or stream requests are in use anywhere in the solution.
|
||||
|
||||
3. **Zero Abstraction Value at Scale**: With only a validation pipeline behavior registered, MediatR 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
|
||||
|
||||
/// <summary>
|
||||
/// Marker interface for command types handled by <see cref="ICommandHandler{TCommand, TResult}"/>.
|
||||
/// </summary>
|
||||
public interface ICommand
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a contract for handling commands in the application layer.
|
||||
/// Commands represent operations that modify application state.
|
||||
/// </summary>
|
||||
/// <typeparam name="TCommand">The type of command to handle.</typeparam>
|
||||
/// <typeparam name="TResult">The type of result returned after handling the command.</typeparam>
|
||||
public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand
|
||||
{
|
||||
Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken = default);
|
||||
}
|
||||
```
|
||||
|
||||
```csharp
|
||||
// src/Lumina.Application/Common/CQRS/IQuery.cs
|
||||
|
||||
/// <summary>
|
||||
/// Marker interface for query types handled by <see cref="IQueryHandler{TQuery, TResult}"/>.
|
||||
/// </summary>
|
||||
public interface IQuery
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines a contract for handling queries in the application layer.
|
||||
/// Queries represent read operations that do not modify application state.
|
||||
/// </summary>
|
||||
/// <typeparam name="TQuery">The type of query to handle.</typeparam>
|
||||
/// <typeparam name="TResult">The type of result returned after handling the query.</typeparam>
|
||||
public interface IQueryHandler<in TQuery, TResult> where TQuery : IQuery
|
||||
{
|
||||
Task<TResult> 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<ErrorOr<IEnumerable<NismResponse>>>;
|
||||
internal sealed class GetConfiguredNismsEndpoint : IGetConfiguredNismsEndpoint
|
||||
{
|
||||
private readonly ISender _sender;
|
||||
|
||||
public GetConfiguredNismsEndpoint(ISender sender)
|
||||
{
|
||||
_sender = sender;
|
||||
}
|
||||
|
||||
public async Task<ErrorOr<IEnumerable<NismResponse>>> 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<GetConfiguredNismsQuery, ErrorOr<IEnumerable<NismResponse>>> _handler;
|
||||
|
||||
public GetConfiguredNismsEndpoint(IQueryHandler<GetConfiguredNismsQuery, ErrorOr<IEnumerable<NismResponse>>> handler)
|
||||
{
|
||||
_handler = handler;
|
||||
}
|
||||
|
||||
public async Task<ErrorOr<IEnumerable<NismResponse>>> 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<T>` 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.
|
||||
+184
@@ -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<in TRequest>
|
||||
{
|
||||
List<Error> Validate(TRequest instance);
|
||||
}
|
||||
|
||||
// IValidationRule.cs - internal rule evaluation contract
|
||||
internal interface IValidationRule<in TRequest>
|
||||
{
|
||||
Error? Validate(TRequest instance);
|
||||
}
|
||||
|
||||
// IRuleBuilder.cs - fluent configuration surface
|
||||
public interface IRuleBuilder<TRequest, TProperty>
|
||||
{
|
||||
IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate);
|
||||
IRuleBuilder<TRequest, TProperty> When(Func<TRequest, bool> condition);
|
||||
IRuleBuilder<TRequest, TProperty> WithError(Error error);
|
||||
}
|
||||
```
|
||||
|
||||
### Base Validator
|
||||
|
||||
```csharp
|
||||
// AbstractValidator.cs
|
||||
public abstract class AbstractValidator<TRequest> : IValidator<TRequest>
|
||||
{
|
||||
private readonly List<IValidationRule<TRequest>> _rules = [];
|
||||
|
||||
protected IRuleBuilder<TRequest, TProperty> RuleFor<TProperty>(
|
||||
Func<TRequest, TProperty> propertySelector)
|
||||
{
|
||||
ValidationRule<TRequest, TProperty> rule = new(propertySelector);
|
||||
_rules.Add(rule);
|
||||
return rule;
|
||||
}
|
||||
|
||||
public List<Error> Validate(TRequest instance)
|
||||
{
|
||||
List<Error> errors = [];
|
||||
foreach (IValidationRule<TRequest> 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<TRequest, TProperty>
|
||||
: IValidationRule<TRequest>, IRuleBuilder<TRequest, TProperty>
|
||||
{
|
||||
private readonly Func<TRequest, TProperty> _propertySelector;
|
||||
private readonly List<Func<TProperty, bool>> _predicates = [];
|
||||
private Error _error = Error.Validation();
|
||||
private Func<TRequest, bool>? _condition;
|
||||
|
||||
public ValidationRule(Func<TRequest, TProperty> propertySelector)
|
||||
=> _propertySelector = propertySelector;
|
||||
|
||||
public IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate)
|
||||
{
|
||||
_predicates.Add(predicate);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRuleBuilder<TRequest, TProperty> When(Func<TRequest, bool> condition)
|
||||
{
|
||||
_condition = condition;
|
||||
return this;
|
||||
}
|
||||
|
||||
public IRuleBuilder<TRequest, TProperty> 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<TRequest, TProperty>` via `ValidatorUtilities`, placed in `Lumina.Application.Common.Utilities`:
|
||||
|
||||
| Extension | Overloads | Behaviour |
|
||||
|---|---|---|
|
||||
| `NotEmpty()` | `string`, `List<TItem>` | 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<CreateSensorCommand>
|
||||
{
|
||||
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<Error>` 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.
|
||||
Reference in new issue
Block a user