title: Register both generic and specific implementation of an interface with ASP.NET Core DI
body: <p>I've read the Armen Shimoon's article <a href="http://dotnetliberty.com/index.php/2016/05/09/asp-net-core-factory-pattern-dependency-injection/" rel="nofollow noreferrer">ASP.NET Core: Factory Pattern Dependency Injection</a> and I've decided to solve my ASP.NET Core DI problem using the technique suggested by him.
  I’ve got a generic interface: </p>
  
  <pre><code>public interface IItemRepository&lt;out T&gt; where T : BaseItem
  </code></pre>
  
  <p>and its generic implementation:</p>
  
  <pre><code>public class ItemRepository&lt;T&gt; : IItemRepository&lt;T&gt; where T : BaseItem
  </code></pre>
  
  <p>I register it with:</p>
  
  <pre><code>services.AddSingleton(typeof(IItemRepository&lt;&gt;), typeof(ItemRepository&lt;&gt;));
  </code></pre>
  
  <p>But for <strong>Currency</strong> I’ve got a specific implementation:</p>
  
  <pre><code>public class CurrencyRepository : ItemRepository&lt;Currency&gt;
  </code></pre>
  
  <p>(Curency is of the <strong>BaseItem</strong> type.) What I want is to register</p>
  
  <pre><code>CurrencyRepository
  </code></pre>
  
  <p>for </p>
  
  <pre><code>IItemRepository&lt;Currency&gt;
  </code></pre>
  
  <p>and </p>
  
  <pre><code>ItemRepository&lt;T&gt;
  </code></pre>
  
  <p>for all other items that implement <strong>BaseItem</strong>. I created a factory class to accomplish this:</p>
  
  <pre><code>public class ItemRepositoryFactory : IServiceFactory> where T : BaseItem
  {
      private readonly ApplicationDbContext _context;
  
      public ItemRepositoryFactory(ApplicationDbContext context)
      {
          _context = context;
      }
  
      public ItemRepository Build()
      {
          if (typeof(T) == typeof(Currency))
              return new CurrencyRepository(_context) as ItemRepository;
  
          return new ItemRepository(_context);
      }
  }
  </code></pre>
  
  <p>but I don’t know how to register it with <strong>IServiceCollection</strong>. Or maybe I’m not on the right way at all?</p>