Overview
Behaviors wrap around handler execution, forming a pipeline where each behavior can execute logic before and after the handler runs. They are similar to middleware in ASP.NET Core.ValidationBehavior
The ValidationBehavior automatically validates commands using FluentValidation before they reach the handler.Implementation
BuildingBlocks/Behaviors/ValidationBehavior.cs
Key Features
- Automatic Validation: Runs all registered validators for the command
- Parallel Execution: Validates using
Task.WhenAllfor performance - Early Exit: Throws
ValidationExceptionbefore handler executes if validation fails - Commands Only: Only applies to
ICommand<TResponse>types, not queries
Creating Validators
Create validators using FluentValidation:Registration
Register validators and the validation behavior:LoggingBehavior
The LoggingBehavior logs request execution, measures performance, and warns about slow operations.Implementation
BuildingBlocks/Behaviors/LoggingBehavior.cs
Key Features
- Request Logging: Logs the start of request processing with request data
- Performance Monitoring: Measures execution time using
Stopwatch - Performance Warnings: Logs warnings for requests taking more than 3 seconds
- Completion Logging: Logs when request handling completes
- Universal: Applies to both commands and queries
Log Output Examples
Normal Request:Registration
Register the logging behavior in your dependency injection:Behavior Order
The order in which behaviors are registered matters. They form a pipeline:Creating Custom Behaviors
You can create additional behaviors for other cross-cutting concerns:Authorization Behavior Example
Caching Behavior Example
Best Practices
Keep Behaviors Generic
Keep Behaviors Generic
Behaviors should handle cross-cutting concerns that apply to many requests, not specific business logic.
Consider Performance
Consider Performance
Behaviors execute for every request. Keep them lightweight and efficient.
Handle Exceptions Carefully
Handle Exceptions Carefully
Exceptions thrown in behaviors prevent the handler from executing.
Related Topics
CQRS Pattern
Learn about commands and queries that behaviors wrap
Exception Handling
See how validation exceptions are handled globally
