I am having trouble with asp.net core dependency injection, I cannot resolve generic interface from IServiceProvider. Here is my setup:
Generic interfaces:
public interface IRequest<out TResponse> {...}
public interface IRequestHandler<TRequest, TResult>
where TRequest : IRequest<TResult> {...}
Concrete implementation:
public class GetUsersQuery : IRequest<IEnumerable<GetUsersResult>> {...}
public abstract class RequestHandler<TRequest, TResult>
: IRequestHandler<TRequest, TResult>
where TRequest : IRequest<TResult> {...}
public class GetUsersQueryHandler
: RequestHandler<GetUsersQuery, IEnumerable<GetUsersResult>> {...}
Then I have a service factory were I register dependency injection like this:
public static void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IRequestHandler<GetUsersQuery,
IEnumerable<GetUsersResult>>, GetUsersQueryHandler>();
}
I can successfully resolve my handler like this:
var handler =
_services.GetService<IRequestHandler<GetUsersQuery, IEnumerable<GetUsersResult>>>();
However, I would like to have a generic method in this factory that receives concrete implementation of IRequest and returns the appropriate handler without knowing the exact type beforehand, something like this:
public Task<TResult> Execute<TResult>(IRequest<TResult> request)
{
var handler =
_services.GetService<IRequestHandler<IRequest<TResult>, TResult>>();
return handler.ExecuteAsync(request);
}
And call this method like this:
_serviceFactory.Execute(new GetUsersQuery(){});
Unfortunately this doesn't work, handler is not resolved and is null. I feel like this should be possible though.
Could you please tell me what I am doing wrong and how to achieve this?