Jan 1 2024
public interface IPipelineBehavior<TRequest, TResponse>
{
Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next);
}
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
// Pre-processing
_logger.LogInformation($"Handling {typeof(TRequest).Name}");
var response = await next();
// Post-processing
_logger.LogInformation($"Handled {typeof(TResponse).Name}");
return response;
}
}
services.AddTransient(typeof(IPipelineBehavior<, ), typeof(LoggingBehavior<, )));
public class MyRequest : IRequest<MyResponse>
{
// Request properties
}
public class MyRequestHandler : IRequestHandler<MyRequest, MyResponse>
{
public async Task<MyResponse> Handle(MyRequest request, CancellationToken cancellationToken)
{
// Handle the request
return new MyResponse();
}
}
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.