Use MediatR with FluentValidation in the ASP.Net Core pipeline

What is is?

For a while I am using MediatR to handle messages in my ASP.Net Core applications. (New to the Mediator design pattern, refactoring.guru has an exelent article about it)
These messages (i.e. of type IRequest) need to be validated before the Handler processes them.
In order to have this done, Fluent Validation is used and called in the Handler.

The process steps would look like this:

  1. API endpoint receives request
  2. Sends the request to the mediator
  3. Mediator finds the correct handler for this request
  4. Handler calls the validation class (containing the Fluent Validation code)
  5. Return the correct response

In order to easily use the MediatR pattern during development, Jeffrey and I wrote a Visual Studio Template for this.

The issue with this approach

This approach, where the handler is responsible to check if the request is valid, creates the posibility that it is forgotten (well, the template makes it easy, but it can be removed / commented out).

Currently every handler contains the following code:

In order to solve this, I wanted to have the validation in the pipeline just like Mateusz has done, but with some different validation failure handling.

Create the pipeline behaviour

In order to have this in the pipeline, the following changes had to be made to the project

  1. Create a custom implementation of IPipelineBehavior (also described on the wiki of MediatR)
  2. Configure services to support the new pipeline behavior
  3. Remove all validation code from the existing handlers
1. Custom implementation of IPipelineBehavior
2. Configure services
3. Removing code and as a result 132 MediatR handlers got cleaner

The result

Much cleaner code (less is more!) and no more nightmares if some of the 132 (and counting) handlers is missing the validation part

Leave a Reply

Your email address will not be published. Required fields are marked *