title: c# generic types and repository pattern
body: <p>I am working on a C# MVC application using the repository pattern. I am using Unity as my IoC in order to implement my repository within the MVC application.</p>
  
  <p>I have created the following generic type with the goal of minimizing code replication throughout my applications. Here is a sample:</p>
  
  <pre><code>public abstract class GenericRepository&lt;T, C&gt; : IDisposable,IGenericRepository&lt;T&gt; where T : class where C : DbContext, new()
  
  
  public async void AddObjectAsync&lt;T&gt;(T entity) where T : class
      {
          try
          {
              // Validate that that there is not an existing object in the database.
              var x = _context.Entry(entity);
              if (!Exists(entity))
              {
                  _context.Set&lt;T&gt;().Add(entity); // Add the entry if it does not exist.
                  _context.SaveChanges();
              }
              else
              {
                  UpdateObjectAsync(entity); // Update the entry if it did exist.
              }
          }
          catch
          {
              throw;
          }
  </code></pre>
  
  <p>This is working great when I use a TPC or TPH strategy, however it does not play well with a TPT strategy. An Example:</p>
  
  <pre><code>public abstract class Component
  {
      [Key]
      public Guid ComponentId { get; set; }
  
      public string Manufacturer { get; set; }
  }
  public class SpecialComponent : Component
  {
      public string ExtraSpecialProperty { get; set; }
  }
  </code></pre>
  
  <p>My implementation within the ComponentRepository:</p>
  
  <pre><code>public class ComponentRepository : GenericRepository&lt;Component, HappyDbContext&gt;, IComponentRepository
  {
  public async void AddComponentAsync&lt;T&gt;(T component) where T : class
      {
          try
          {
  
              if(component != null)
              {
                  AddObjectAsync(component);
              }
              else
              {
              throw new ArgumentNullException();
              }
  
          }
          catch (ArgumentNullException ex)
          {
              _logger.WriteErrorLogAsync(ex);
              throw ex;
          }
      }
  </code></pre>
  
  <p>The first line of this code block is what I am having trouble with. In order to initialize the type GenericRepository I need to insert a class for T. In this case the DbContext C will always be the same so it is not of concern.</p>
  
  <p>How can I implement a fully generic pattern that will work with inherited types? If it were a small number of items then I would be less worried about it, however that is not the case in this situation. I think that there is certainly a better way to handle this, so I am reaching out to you all for your input.</p>