What is it?
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:
API endpoint receives request
Sends the request to the mediator
Mediator finds the correct handler for this request
Handler calls the validation class (containing the Fluent Validation code)
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
- Create a custom implementation of IPipelineBehavior (also described on the wiki of MediatR)
- Configure services to support the new pipeline behavior
- Remove all validation code from the existing handlers
Much cleaner code (less is more!) and no more nightmares if some of the 132 (and counting) handlers is missing the validation part