I recently started a new project where we are using MediatR to simplify our CQRS infrastructure. This gives us our basic building blocks to create our queries, commands and the related handlers.
One of the things I wanted to add were some decorators to provide some extra functionality(like authorization, logging, transaction management,…) before and after a request. Turns out I’m lucky as with the release of MediatR 3.0 I can fall back to a built-in functionality called behaviors.
Similar to action filters in ASP.NET MVC, it gives me the opportunity to execute some arbitrary logic before and after a request(command/query). Usage is simple:
- You have to implement the IPipelineBehavior<TRequest, TResponse> interface:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> | |
{ | |
private readonly ILogger _logger; | |
public LoggingBehavior(ILogger logger) | |
{ | |
_logger=logger; | |
} | |
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next) | |
{ | |
_logger.Information($"Handling {typeof(TRequest).Name}"); | |
var response = await next(); | |
_logger.Information($"Handled {typeof(TResponse).Name}"); | |
return response; | |
} | |
} |
- Don’t forget to register the pipeline behavior through your IoC container(StructureMap in the example below)!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InfrastructureRegistry : Registry | |
{ | |
public InfrastructureRegistry() | |
{ | |
For(typeof(IPipelineBehavior<,>)).Add(typeof(LoggingBehavior<,>)); | |
} | |
} |