MediatR FluentValidation Pipeline - ChrispyPeaches/FocusFriends GitHub Wiki

MediatR

Definition

  • MediatR is a package that facilitates the process of method execution.

Purpose

  • Using MediatR allows units of code to be written in isolation, and easily called.
  • This allows us to decouple methods from any application infrastructure they would have been a part of, i.e., controllers.
  • Additionally, the isolation afforded by MediatR allows for ease of testing, as all units of code have minimal dependencies, and can be easily mocked.

FluentValidation

Definition

  • FluentValidation is a package that facilitates the process of data validation.

Purpose

  • Using FluentValidation allows us as developers to quickly assess incoming data against a set of predefined rules.
  • Validators are objects that inherent from the FluentValidation class AbstractValidator<TRequest,TResponse>, wherein rules are defined that place restrictions on incoming data.
  • Validators ensure that all data coming into a function is appropriate and ready for processing.

MediatR / FluentValidation Pipeline

What is the pipeline?

  • The MediatR / FluentValidation pipeline is a critical piece of our backend infrastructure that ensures any command or query sent via the mediator's Send method is validated prior to function execution.

How is the pipeline implemented?

  • The pipeline is implemented via the creation of a "PipelineBehavior" that intercepts the mediator's Send method, and attempts validation on the incoming command/query prior to the target function's execution.
  • The interception of the mediator's Send method is defined within FocusAPI/Configuration/PipelineBehaviors/ValidationBehavior.cs

How do I use the pipeline to ensure incoming information is valid?

  • In order to ensure incoming data is valid prior to function execution, a validator must be defined for the command or query. (Validators are defined in FocusCore/Validators)
  • Within the newly created validator's constructor, rules for validation must be defined.
  • After configuring the validator for the command or query, the mediator will be aware of the validators existence, and will ensure the command or query is validated upon calling the mediator's Send method.