title: .NET Core dependency injection, resolve generic interface
body: <p>I am having trouble with asp.net core dependency injection, I cannot resolve generic interface from IServiceProvider. Here is my setup: </p>
  
  <p>Generic interfaces:</p>
  
  <pre><code>public interface IRequest&lt;out TResponse&gt; {...}
  
  public interface IRequestHandler&lt;TRequest, TResult&gt; 
      where TRequest : IRequest&lt;TResult&gt; {...}
  </code></pre>
  
  <p>Concrete implementation:</p>
  
  <pre><code>public class GetUsersQuery : IRequest&lt;IEnumerable&lt;GetUsersResult&gt;&gt; {...}
  
  public abstract class RequestHandler&lt;TRequest, TResult&gt; 
      : IRequestHandler&lt;TRequest, TResult&gt;
      where TRequest : IRequest&lt;TResult&gt; {...}
  
  public class GetUsersQueryHandler
      : RequestHandler&lt;GetUsersQuery, IEnumerable&lt;GetUsersResult&gt;&gt; {...}
  </code></pre>
  
  <p>Then I have a service factory were I register dependency injection like this:</p>
  
  <pre><code>public static void ConfigureServices(IServiceCollection services)
  {
      services.AddTransient&lt;IRequestHandler&lt;GetUsersQuery, 
      IEnumerable&lt;GetUsersResult&gt;&gt;, GetUsersQueryHandler&gt;();
  }
  </code></pre>
  
  <p>I can successfully resolve my handler like this:</p>
  
  <pre><code>var handler = 
  _services.GetService&lt;IRequestHandler&lt;GetUsersQuery, IEnumerable&lt;GetUsersResult&gt;&gt;&gt;();
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>public Task&lt;TResult&gt; Execute&lt;TResult&gt;(IRequest&lt;TResult&gt; request)
  {
      var handler =
          _services.GetService&lt;IRequestHandler&lt;IRequest&lt;TResult&gt;, TResult&gt;&gt;();
      return handler.ExecuteAsync(request);
  }
  </code></pre>
  
  <p>And call this method like this:</p>
  
  <pre><code>_serviceFactory.Execute(new GetUsersQuery(){});
  </code></pre>
  
  <p>Unfortunately this doesn't work, handler is not resolved and is null. I feel like this should be possible though. </p>
  
  <p>Could you please tell me what I am doing wrong and how to achieve this?</p>