MediatR Pipeline Behaviors and Fluent Validation in NET 8 Microservices

Mehmet Ozkaya
3 min readMar 25, 2024

--

When you’re building apps with .NET, there are cool tools called MediatR and Fluent Validation that can really help out.

🌐MediatR: Elevating Request Handling

MediatR is a popular library in .NET used for implementing the mediator pattern. One of its powerful features is ‘Pipeline Behaviors’, which allows us to introduce additional logic into the request handling process, such as validation, logging, exception handling and performance tracking.

I have just published course — .NET 8 Microservices: C# 12, DDD, CQRS, Vertical/Clean Architecture.

💡The Role of Pipeline Behaviors

Pipeline Behaviors serve as the MediatR library’s middleware, encapsulating the request handling process. This design enables the seamless integration of essential operations like validation and logging, ensuring they remain unobtrusive to the core business logic.

Pipeline Behaviors act as middleware in the MediatR library. They wrap around the request handling process, enabling us to implement cross-cutting concerns without cluttering the handlers themselves.

Example of Logging Behavior

🛠️Create MediatR Pipeline Behavior

Creating a pipeline behavior involves defining a class that adheres to the IPipelineBehavior<TRequest, TResponse> interface. This setup allows the insertion of pre- and post-request handling logic, offering a flexible framework for enhancing functionality.

public class PerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
// Pre-request logic: Start timer
var timer = Stopwatch.StartNew();
// Proceed with the handler
var response = await next();
// Post-request logic: Log elapsed time
timer.Stop();
var elapsedMilliseconds = timer.ElapsedMilliseconds;
// Log or handle the timing information
return response;
}
}

🏗 Fluent Validation: Mastering Data Integrity

Fluent Validation is a .NET library for building strongly-typed validation rules. Fluent Validation emerges as a powerful library for crafting expressive and type-safe validation rules, ensuring that data adheres to business constraints before being processed.

🌐Integrating Fluent Validation with MediatR

We can integrate Fluent Validation with MediatR to validate requests before they reach the actual handler. The synergy between Fluent Validation and MediatR shines within pipeline behaviors, where validation can be applied directly to incoming requests, safeguarding against invalid data reaching business logic handlers.

🏗️Constructing Validation Rules

Fluent Validation allows you to define validation rules in separate classes, using a fluent interface to specify conditions that each property of your models must satisfy. Fluent Validation excels in defining validation rules through a fluent API, allowing for clear and concise specification of property constraints.

public class CreateProductCommandValidator : AbstractValidator<CreateProductCommand>
{
public CreateProductCommandValidator()
{
RuleFor(command => command.Name).NotEmpty().WithMessage("Product name is required.");
RuleFor(command => command.Price).GreaterThan(0).WithMessage("Product price must be greater than zero.");
// Additional rules...
}
}

Uniting MediatR and Fluent Validation

The combination of MediatR’s pipeline behaviors with Fluent Validation’s rule engine fosters a centralized and streamlined approach to managing validations and other cross-cutting concerns. This integration ensures that business handlers are presented with only valid data, reinforcing application reliability and maintainability.

🚀 Conclusion

MediatR Pipeline Behaviors and Fluent Validation stand as pillars for developing .NET applications that are not only robust but also adhere to the principles of clean architecture. By embracing these tools, developers can ensure their applications are equipped to handle complex business requirements while maintaining a clear separation of concerns.

I have just published course — .NET 8 Microservices: C# 12, DDD, CQRS, Vertical/Clean Architecture.

This is step-by-step development of reference microservices architecture that include microservices on .NET platforms which used ASP.NET Web API, Docker, RabbitMQ, MassTransit, Grpc, Yarp API Gateway, PostgreSQL, Redis, SQLite, SqlServer, Marten, Entity Framework Core, CQRS, MediatR, DDD, Vertical and Clean Architecture implementation with using latest features of .NET 8 and C# 12.

--

--

Mehmet Ozkaya

Software Architect | Udemy Instructor | AWS Community Builder | Cloud-Native and Serverless Event-driven Microservices https://github.com/mehmetozkaya