Skip to content

Message validation using DataAnnotations and FluentValidation

License

Notifications You must be signed in to change notification settings

NServiceBusExtensions/NServiceBus.Validation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NServiceBus Validation

Build status NuGet Status NuGet Status

Message validation using DataAnnotations and FluentValidation.

See Milestones for release notes.

Already a Patron? skip past this section

Community backed

It is expected that all developers either become a Patron to use NServiceBusExtensions. Go to licensing FAQ

Sponsors

Support this project by becoming a Sponsor. The company avatar will show up here with a website link. The avatar will also be added to all GitHub repositories under the NServiceBusExtensions organization.

Patrons

Thanks to all the backing developers. Support this project by becoming a patron.

NServiceBus.FluentValidation

Uses FluentValidation to validate incoming and outgoing messages.

NuGet package

https://www.nuget.org/packages/NServiceBus.FluentValidation/

Usage

FluentValidation message validation can be enabled using the following:

endpointConfiguration.UseFluentValidation();
serviceCollection.AddValidatorsFromAssemblyContaining<TheMessage>();

snippet source | anchor

This will result in, when an invalid message being detected, a validation exception being thrown and that message being handled by Recoverability. The validation exception will also be added to Unrecoverable exceptions to avoid unnecessary retries.

By default, incoming and outgoing messages are validated.

To disable for incoming messages use the following:

endpointConfiguration.UseFluentValidation(incoming: false);

snippet source | anchor

To disable for outgoing messages use the following:

endpointConfiguration.UseFluentValidation(outgoing: false);

snippet source | anchor

Enabling validation on outgoing message will result in the validation exception be thrown in the context of the sender, instead of during message processing on the receiving endpoint. This can be particularly helpful in development and/or debugging scenarios since the stack trace and debugger will more accurately reflect the cause of the invalid message.

Messages can then have an associated validator:

public class TheMessage :
    IMessage
{
    public string Content { get; set; } = null!;
}

public class MyMessageValidator :
    AbstractValidator<TheMessage>
{
    public MyMessageValidator() =>
        RuleFor(_ => _.Content)
            .NotEmpty();
}

snippet source | anchor

Accessing the current pipeline context

In some cases a validator may need to use data from the current message context.

The current message context can be accessed via two extension methods:

  • The current message headers can be accessed via FluentValidationExtensions.Headers(this CustomContext customContext)
  • The current ContextBag can be accessed via FluentValidationExtensions.ContextBag(this CustomContext customContext).

public class ContextValidator :
    AbstractValidator<TheMessage>
{
    public ContextValidator() =>
        RuleFor(_ => _.Content)
            .Custom((propertyValue, validationContext) =>
            {
                var messageHeaders = validationContext.Headers();
                var bag = validationContext.ContextBag();
                if (propertyValue != "User" ||
                    messageHeaders.ContainsKey("Auth"))
                {
                    return;
                }

                validationContext.AddFailure("Expected Auth header to exist");
            });
}

snippet source | anchor

Validator scanning

Validators are registered and resolved using dependency injection. Assemblies can be added for validator scanning using either a generic Type, a Type instance, or an assembly instance.

endpointConfiguration.UseFluentValidation();
serviceCollection.AddValidatorsFromAssemblyContaining<MyMessage>();
serviceCollection.AddValidatorsFromAssemblyContaining(typeof(SomeOtherMessage));
serviceCollection.AddValidatorsFromAssembly(assembly);

snippet source | anchor

By default, there are two exception scenarios when adding validators. An exception will be thrown if:

  • No validators are found in an assembly that is scanned.
  • Any non-public validators are found in an assembly that is scanned.

These exception scenarios can be excluded using the following:

endpointConfiguration.UseFluentValidation();
serviceCollection.AddValidatorsFromAssembly(
    assembly,
    throwForNonPublicValidators: false,
    throwForNoValidatorsFound: false);

snippet source | anchor

NServiceBus.DataAnnotations

Uses System.ComponentModel.DataAnnotations to validate incoming and outgoing messages.

NuGet package

https://www.nuget.org/packages/NServiceBus.DataAnnotations/

Usage

DataAnnotations message validation can be enabled using the following:

configuration.UseDataAnnotationsValidation();

snippet source | anchor

This will result in, when an invalid message being detected, a validation exception being thrown and that message being handled by Recoverability. The validation exception will also be added to Unrecoverable exceptions to avoid unnecessary retries.

By default, incoming and outgoing messages are validated.

To disable for incoming messages use the following:

configuration.UseDataAnnotationsValidation(incoming: false);

snippet source | anchor

To disable for outgoing messages use the following:

configuration.UseDataAnnotationsValidation(outgoing: false);

snippet source | anchor

Enabling validation on outgoing message will result in the validation exception be thrown in the context of the sender, instead of during message processing on the receiving endpoint. This can be particularly helpful in development and/or debugging scenarios since the stack trace and debugger will more accurately reflect the cause of the invalid message.

Messages can then be decorated with DataAnnotations attributes. For example, to make a property required use the RequiredAttribute:

public class TheMessage :
    IMessage
{
    [Required]
    public string Content { get; set; } = null!;
}

snippet source | anchor

Icon

Validation designed by Becris from The Noun Project.

About

Message validation using DataAnnotations and FluentValidation

Resources

License

Security policy

Stars

Watchers

Forks