C#. Implementation of MediatR library

38 views Asked by At

I have several questions regarding implementations of MediatR.

public class RequestHandlerWrapperImpl<TRequest, TResponse> has Handle method:

public override Task<TResponse> Handle(IRequest<TResponse> request, IServiceProvider serviceProvider,
    CancellationToken cancellationToken)
{
    Task<TResponse> Handler() => serviceProvider.GetRequiredService<IRequestHandler<TRequest, TResponse>>()
        .Handle((TRequest) request, cancellationToken);

    return serviceProvider
        .GetServices<IPipelineBehavior<TRequest, TResponse>>()
        .Reverse()
        .Aggregate((RequestHandlerDelegate<TResponse>) Handler,
            (next, pipeline) => () => pipeline.Handle((TRequest) request, next, cancellationToken))();
}

So it uses GetRequiredService method to find a service when we use for example a sender.Send(new CreateItem()); command.

Sorry if my assumption is not correct, I don't have to much experience in this aria

  1. Can GetRequiredService be considered as example of service locator that is anti pattern?
  2. If it is true why this lib is popular?
  3. Is there any other choice to avoid service locator in this lib implementation?
0

There are 0 answers