FluentValidation adapter for the MessageValidation pipeline — automatically bridge your existing FluentValidation validators into the protocol-agnostic message validation pipeline.
dotnet add package MessageValidation.FluentValidationpublic class TemperatureReading
{
public string SensorId { get; set; } = "";
public double Value { get; set; }
public DateTime Timestamp { get; set; }
}Write a standard FluentValidation AbstractValidator<T> — no special base class required:
using FluentValidation;
public class TemperatureReadingValidator : AbstractValidator<TemperatureReading>
{
public TemperatureReadingValidator()
{
RuleFor(x => x.SensorId).NotEmpty();
RuleFor(x => x.Value).InclusiveBetween(-50, 150);
RuleFor(x => x.Timestamp).LessThanOrEqualTo(DateTime.UtcNow);
}
}using MessageValidation;
using MessageValidation.FluentValidation;
builder.Services.AddMessageValidation(options =>
{
options.MapSource<TemperatureReading>("sensors/+/temperature");
options.DefaultFailureBehavior = FailureBehavior.Log;
});
// Scan the assembly for all AbstractValidator<T> implementations
// and register the FluentValidation adapter as the IMessageValidator<T> bridge.
builder.Services.AddMessageFluentValidation(typeof(Program).Assembly);
builder.Services.AddMessageDeserializer<JsonMessageDeserializer>();
builder.Services.AddMessageHandler<TemperatureReading, TemperatureHandler>();That's it. The pipeline will now use your TemperatureReadingValidator automatically when a TemperatureReading message arrives.
AddMessageFluentValidation does two things:
- Scans assemblies for all
AbstractValidator<T>implementations and registers them in the DI container (viaFluentValidation.DependencyInjectionExtensions). - Registers an open-generic adapter (
FluentValidationMessageValidator<T>) that implementsIMessageValidator<T>by delegating to FluentValidation'sIValidator<T>.
IMessageValidator<T>
└── FluentValidationMessageValidator<T>
└── IValidator<T> (your AbstractValidator<T>)
| Parameter | Description |
|---|---|
assemblies |
Assemblies to scan for AbstractValidator<T> implementations. If none are provided, the calling assembly is scanned. |
// Scan specific assemblies
builder.Services.AddMessageFluentValidation(
typeof(TemperatureReadingValidator).Assembly,
typeof(DeviceHeartbeatValidator).Assembly);
// Or scan the calling assembly (default)
builder.Services.AddMessageFluentValidation();- .NET 10+
- MessageValidation core package
- FluentValidation 11+