EDIT: Solution from @lilasquared
Am I doing something wrong here? This happens using pre and post processors
public class MediatRInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddMediatR(typeof(CreateCustomerCommand).Assembly);
services.AddScoped(typeof(IRequestPostProcessor<,>), typeof(LoggingBehavior<,>));
}
}
public class LoggingBehavior<TRequest, TResponse> : IRequestPostProcessor<TRequest, TResponse>
{
public Task Process(TRequest request, TResponse response, CancellationToken cancellationToken)
{
Log.Information($"Handled {typeof(TRequest).DeclaringType?.Name ?? typeof(TRequest).Name}");
return Task.CompletedTask;
}
}
After one web request:
08 Jan 2020 10:07:06.507 Handled GetCustomersQuery
08 Jan 2020 10:07:00.679 Handled GetCustomersQuery
the AddMediatR method already connects implementations to types closing the pre and post request processors, so you do not need this line services.AddScoped(typeof(IRequestPostProcessor<,>), typeof(LoggingBehavior<,>));
you only need to register actual pipeline behaviors manually.
@lilasquared Thank you!!
It were nice if that behaviour would be documented. It took me some time to find this explanation.
the documentation is here https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection
Thanks for the link. IMHO this is an important information and should be mentioned or linked in the docs.
It could be added with the explicit notation that this function is only for aspnet core and only if you include the extension method package. TBH if you are using the MediatR.Extensions.Microsoft.DependencyInjection package and methods from it, I would expect the documentation to be nearest to that project, which it is.
in fact, the main wiki (https://github.com/jbogard/MediatR/wiki#aspnet-core) DOES have this link
ASP.NET Core
If you're using ASP.NET Core then you can skip the configuration and use MediatR's MediatR.Extensions.Microsoft.DependencyInjection package which includes a IServiceCollection.AddMediatR(Assembly) extension method, allowing you to register all handlers and pre/post-processors in a given assembly.
Most helpful comment
the AddMediatR method already connects implementations to types closing the pre and post request processors, so you do not need this line
services.AddScoped(typeof(IRequestPostProcessor<,>), typeof(LoggingBehavior<,>));you only need to register actual pipeline behaviors manually.