Skip to content

6.2. FluentValidation

Mikołaj Milewski edited this page Nov 12, 2026 · 1 revision

FluentValidation

Stateflows.Extensions.FluentValidation connects FluentValidation validators to Stateflows' event validation pipeline. FluentValidation errors are converted into System.ComponentModel.DataAnnotations.ValidationResult values, so an invalid event follows the normal Stateflows validation behavior.

Install the extension and register it along with your FluentValidation validators:

using FluentValidation;
using Stateflows;

services.AddStateflows(stateflows => stateflows
    .AddFluentValidation()
    .AddStateMachines(machines => machines
        .AddStateMachine<Order>()));

services.AddSingleton<IValidator<ConfirmOrder>, ConfirmOrderValidator>();

Validators are resolved from dependency injection by the exact event type being validated. If no validator is registered for that type, this extension contributes no FluentValidation errors. For a structural event, it can also resolve an IValidator<StructuralEvent> when no validator is registered for a more specific CLR event type.

public sealed record ConfirmOrder(string Email);

public sealed class ConfirmOrderValidator : AbstractValidator<ConfirmOrder>
{
    public ConfirmOrderValidator()
    {
        RuleFor(order => order.Email).EmailAddress();
    }
}

Register FluentValidation services in the same service collection used by Stateflows. Other Stateflows validators may also participate in validation; this extension adapts FluentValidation results rather than replacing the core validation pipeline. See the project source.

Clone this wiki locally