title: C# asp.net core generic factory method dependency injection
body: <p>I am using asp.net core, when adding my service to dependency injection i have a following scenario:</p>
  
  <pre><code>        // TODO Need to have generalized code for following Repositories
          services.AddScoped(s =&gt; s.GetRequiredService&lt;IRepositoryFactory&gt;().CreateRepository&lt;Customer&gt;(services));
          services.AddScoped(s =&gt; s.GetRequiredService&lt;IRepositoryFactory&gt;().CreateRepository&lt;CustomerCategory&gt;(services));
          services.AddScoped(s =&gt; s.GetRequiredService&lt;IRepositoryFactory&gt;().CreateRepository&lt;SaleOrder&gt;(services));
  </code></pre>
  
  <p>In this case i am mentioning "T" explicitly which will be headache when model grows, my CreateRepository method is as follows:  </p>
  
  <pre><code>    public IRepository&lt;T&gt; CreateRepository&lt;T&gt;(IServiceCollection services) where T : class 
      {
  
          if (typeof(T).IsAssignableFrom(typeof(IAuditable)))
              return _provider.GetRequiredService&lt;AuditableRepository&lt;T&gt;&gt;();
          else if (typeof(T).IsAssignableFrom(typeof(IArchivable)))
              return _provider.GetRequiredService&lt;ArchivableRepository&lt;T&gt;&gt;();
  
          //return new Repository&lt;T&gt;(_provider.GetRequiredService&lt;DbContext&gt;());
          return _provider.GetRequiredService&lt;Repository&lt;T&gt;&gt;();
      }
  </code></pre>
  
  <p>I want some thing like:</p>
  
  <pre><code>services.TryAdd(ServiceDescriptor.Scoped(typeof(IRepository&lt;&gt;), s.GetRequiredService&lt;IRepositoryFactory&gt;().CreateRepository&lt;&gt;(services)));
  </code></pre>
  
  <p>Thanx in advance.</p>