jbogard / MediatR

Simple, unambitious mediator implementation in .NET
Apache License 2.0
11k stars 1.16k forks source link

Why not directly invoke _serviceProvider.GetRequiredService #903

Closed huiyuanai709 closed 1 year ago

huiyuanai709 commented 1 year ago

In Mediator.cs

public Task<TResponse> Send<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default)
    {
        if (request == null)
        {
            throw new ArgumentNullException(nameof(request));
        }

        var handler = (RequestHandlerWrapper<TResponse>)_requestHandlers.GetOrAdd(request.GetType(), static requestType =>
        {
            var wrapperType = typeof(RequestHandlerWrapperImpl<,>).MakeGenericType(requestType, typeof(TResponse));
            var wrapper = Activator.CreateInstance(wrapperType) ?? throw new InvalidOperationException($"Could not create wrapper type for {requestType}");
            return (RequestHandlerBase)wrapper;
        });

        return handler.Handle(request, _serviceProvider, cancellationToken);
    }

why not directly call

public Task<TResponse> Send<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default)
    {
        if (request == null)
        {
            throw new ArgumentNullException(nameof(request));
        }

        return _serviceProvider.GetRequiredService<IRequestHandler<IRequest<TResponse>, TResponse>>()
            .Handle(request, cancellationToken);
    }
maxime-poulain commented 1 year ago

The RequestHandlerWrapperImpl class contains the logic to resolve the pipeline behavior:

https://github.com/jbogard/MediatR/blob/f33439df4dce11c22550fcf3200069675d92201a/src/MediatR/Wrappers/RequestHandlerWrapper.cs#L37

huiyuanai709 commented 1 year ago

The RequestHandlerWrapperImpl class contains the logic to resolve the pipeline behavior:

https://github.com/jbogard/MediatR/blob/f33439df4dce11c22550fcf3200069675d92201a/src/MediatR/Wrappers/RequestHandlerWrapper.cs#L37

I believe that calling RequestHandlerWrapperImpl is unnecessary. This class does not need to know the specific generic parameters.

jbogard commented 1 year ago

If you can provide a PR that passes all the tests, I'll take a look.