I am trying to implement simple logging behavior using MediatR, and I tried some registration in Program.CS but none of them didn't work.
using MediatR;
using Microsoft.Extensions.Logging;
namespace CAS.TimeSheet.Application.Behaviors;
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
_logger.LogInformation($"Handling {typeof(TRequest).Name}");
var response = await next();
_logger.LogInformation($"Handled {typeof(TResponse).Name}");
return response;
}
}
and
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<HolidayService>();
// cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
// cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
});
// builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
as you see I tried these registration:
cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
Does someone know, what is the problem?
In fact
cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));was working but I had forgotten something about the MediatR. I used post request and it worked.