Path: redb-route/redb.Route.Validation.Adapters/DataAnnotationsValidator.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Validation.Adapters/DataAnnotationsValidator.cs
----
using System.ComponentModel.DataAnnotations;
using redb.Route.Abstractions;
namespace redb.Route.Validation.Adapters;
///
/// Bridges System.ComponentModel.DataAnnotations to redb.Route's .
/// Runs
/// against the exchange body and aggregates errors with their member names.
///
public sealed class DataAnnotationsValidator : IMessageValidator
{
private readonly ValidationSeverity _severity;
private readonly IServiceProvider? _serviceProvider;
///
/// Creates a DataAnnotations-backed message validator.
///
/// Severity for failures (default ).
///
/// Optional propagated to
/// for IValidatableObject implementations that need DI services.
///
public DataAnnotationsValidator(
ValidationSeverity severity = ValidationSeverity.Error,
IServiceProvider? serviceProvider = null)
{
_severity = severity;
_serviceProvider = serviceProvider;
}
///
public ValidationResult Validate(IExchange exchange)
{
ArgumentNullException.ThrowIfNull(exchange);
var body = exchange.In.Body;
if (body is null)
return ValidationResult.Failure(new[] { "Message body is null." }, _severity);
var ctx = new ValidationContext(body, _serviceProvider, items: null);
var results = new List();
var ok = Validator.TryValidateObject(body, ctx, results, validateAllProperties: true);
if (ok)
return ValidationResult.Success();
var errors = results
.Select(r => r.MemberNames.Any()
? $"{string.Join(",", r.MemberNames)}: {r.ErrorMessage}"
: (r.ErrorMessage ?? "Validation failed"))
.ToArray();
return ValidationResult.Failure(errors, _severity);
}
}