MediatR 12.2.0 behavior

123 views Asked by At

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:

  1. cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
  2. cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
  3. builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));

Does someone know, what is the problem?

1

There are 1 answers

0
Hamed Naghdi On

In fact cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); was working but I had forgotten something about the MediatR. I used post request and it worked.