title: Base API Controller with Generics
body: <p>I am trying to implement a simple Base class for my Web API 2 controllers - they should always have a Entity Framework repo and a <code>Dispose</code> method - </p>
  
  <pre><code>public abstract class BaseController&lt;TRepo&gt; : ApiController where TRepo : Repository&lt;EF.DBContext&gt;, new()
  {
      private readonly TRepo _repo;
  
      protected TRepo Repo { get { return _repo; } }
  
  
      protected override void Dispose(bool disposing)
      {
          _repo.Dispose();
          base.Dispose(disposing);
      }
  }
  </code></pre>
  
  <p>The inheriting contoller -</p>
  
  <pre><code>public class EntriesController : BaseController&lt;EntryRepo&gt;
  {
      [HttpGet]
      public IEnumerable&lt;Domain.Transaction.Entry&gt; Get()
      {
          return (Mapper.Map&lt;IEnumerable&lt;Domain.Transaction.Entry&gt;&gt;(Repo.GetAll()));
      }
  
      [HttpPost]
      [SendSignalRNotification]
      public Domain.Transaction.Entry Save(Domain.Transaction.Entry newEntry)
      {
          return (Mapper.Map&lt;Domain.Transaction.Entry&gt;(Repo.Insert(Mapper.Map&lt;EF.Transaction.Entry&gt;(newEntry))));
      }
  }
  </code></pre>
  
  <p>I am having two issues:
  1. The <code>dispose</code> of the <code>BaseController</code> is being called before the action of the child
  2. The <code>_repo</code> is always <code>null</code>, I thought <code>new()</code> would make it instantiate</p>
  
  <p>I am very new to generics and I am clearly nor understanding something. Thanks!</p>
  
  <p>UPDATE:</p>
  
  <pre><code>public abstract class BaseController&lt;TRepo&gt; : ApiController where TRepo : Repository&lt;EF.DBContext&gt;, new()
  {
      private readonly TRepo _repo;
  
      protected TRepo Repo { get { return _repo; } }
  
      protected BaseController()
      {
          _repo = new TRepo();
      }
  
      protected override void Dispose(bool disposing)
      {
          _repo.Dispose();
          base.Dispose(disposing);
      }
  }
  </code></pre>
  
  <p>Per Sergey's comment I have added a constructor to the <code>BaseController</code> and <code>_repo</code> is not null anymore and the data is coming back.</p>
  
  <p>However <code>Dispose</code> is still being called as the first thing in the request for some reason.</p>