Search code examples
asp.net-corecqrsmediatr

How do I register and use a MediatR pipeline handler, for ASP.NET Core?


I'm using ASP.NET Core, the latest MediatR, and MediatR extension for Core's DI.

I'm trying to set up a pipeline with validation, using the official blog post. The example is here.

I don't understand how to register/use that pipeline class. Another blog post shows how to do this, but I think it's for AutoFac.

How do I do this for the built-in container?


Solution

  • The posts you mention use MediatR 2.x.
    MediatR 3.0 has been released not long ago, and has built-in support for pipelines. I would suggest you read the associated documentation.

    In short, MediatR now exposes a IPipelineBehavior<TRequest, TResponse>, and the instances you register in your container will be discovered automatically by MediatR when constructing the handler.

    Here's what it could look like in ASP.NET Core:

    public class MyRequest : IRequest<string>
    {
    }
    
    public class MyRequestHandler : IRequestHandler<MyRequest, string>
    {
        public string Handle(MyRequest message)
        {
            return "Hello!";
        }
    }
    
    public class TracingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    {
        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
        {
            Trace.WriteLine("Before");
            var response = await next();
            Trace.WriteLine("After");
    
            return response;
        }
    }
    

    Very simple, a request, a handler and a behavior that does some "logging".

    Registration is very easy, too:

    var services = new ServiceCollection();
    services.AddMediatR(typeof(Program));
    services.AddTransient(typeof(IPipelineBehavior<,>), typeof(TracingBehaviour<,>));
    var provider = services.BuildServiceProvider();
    
    var mediator = provider.GetRequiredService<IMediator>();
    
    var response = await mediator.Send(new MyRequest());
    

    It's just a matter of registering the open-generic TracingBehavior as a generic implementation of IPipelineBehavior.