title: injecting/resolving generic and none generic services which inherit from same base interface
body: <p>I have some service classes which inherit all from the same non generic interface.<br />
  But some services will not directly inherit it but through some intermediate generic interface.<br />
  Using .NET 6</p>
  <pre class="lang-cs prettyprint-override"><code>public interface IService { }   
  public interface IServiceDirect {}
  public class ServiceDirect: IServiceDirect {}
  
  public interface IGenericInterface&lt;T&gt;: IService{}
  public abstract class AGenericClass&lt;T&gt;: IGenericInterface&lt;T&gt; {}
  public class GenericClass: IGenericInterface&lt;MyEntity&gt; {}
  </code></pre>
  <p>I now have the need to get all services which inherit from IService during runtime.<br />
  Unfortunately calling <code>_serviceProvider.GetServices&lt;IService&gt;()</code> will only return the services which inherit directly (meaning only through non generic interfaces like <code>ServiceDirect</code>) from <code>IService</code></p>
  <p>Here is how I register the services (assembly is just an Assembly provided through a parameter) and I left out some code to select only the classes/interfaces I want.</p>
  <pre class="lang-cs prettyprint-override"><code>assembly.ExportedType.ToList().ForEach(x =&gt; {
    //services is of type IServiceCollection
    services.AddScoped(x.Parent.IsGenericType 
         ? x.Parent.GenericTypeDefinition()
               .MakeGenericType(x.Parent.GetGenericArguments())  
         : x.Parent, x.Class);
  }
  </code></pre>
  <p>So far so good, they get injected and can be resolved when constructor injecting them by their most direct interface or abstract parent (exactly what I usually need).</p>
  <p>To resolve them with <code>_serviceProvider.GetServices&lt;IService&gt;()</code> I have to add a second registration like this in my ForEach</p>
  <pre class="lang-cs prettyprint-override"><code>assembly.ExportedType.ToList().ForEach(x =&gt; {
    if(x.Parent.IsGenericType)
    {
       services.AddScoped(x.Parent.GenericTypeDefinition()
           .MakeGenericType(x.Parent.GetGenericArguments())
               .GetInterfaces().FirstOrDefault(x =&gt; x == typeof(IService)),  
         x.Class);
    }
  
    //services is of type IServiceCollection
    services.AddScoped(x.Parent.IsGenericType 
         ? x.Parent.GenericTypeDefinition().MakeGenericType(
               x.Parent.GetGenericArguments())  
         : x.Parent, x.Class);
  }
  </code></pre>
  <p>Now I can resolve all the services like I need.</p>
  <p>My question is: is there a better way instead of registering every interface I need explicitly?</p>