title: Constructor Dependency Injection in Base Class
body: <p>i'm building a repository base class with Entity Framework where all Entities repository will inherit. I want to inject the <code>DatabaseContext</code> in base class using Dependency Injection using Ninject. I think the Constructor Injection is the right way, but doing this with Constructor Injection in derived class I will must to pass parameter to constructor in base class and I don't want it. Therefore, a Setter Injection is more appropriate?</p>
  
  <p>Here's my code:</p>
  
  <pre><code>public abstract class BaseRepository&lt;TEntity&gt; : IDisposable 
      where TEntity : class
  {
      private readonly DatabaseContext _databaseContext;
  
      protected BaseRepository(DatabaseContext databaseContext)
      {
          this._databaseContext = databaseContext;
      }
  }
  </code></pre>
  
  <p>Using Constructor Injection in the above example, <strong>in my derived class I will must to pass databaseContext object to base class, I don't like to doing this to all my derived class</strong>:</p>
  
  <pre><code>public class UsuarioRepository : BaseRepository&lt;IUsuario&gt;,
      IUsuarioRepository
  {
      public UsuarioRepository(DatabaseContext databaseContext)
          : base(databaseContext)
      {
      }
  }
  </code></pre>
  
  <p>Setter Injection instead of Constructor Injection is a good way to solve that? What is the best way?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Using Setter Injection my derived class's will not have constructors:</p>
  
  <pre><code>public class UsuarioRepository : BaseRepository&lt;IUsuario&gt;, IUsuarioRepository
  {
  }
  </code></pre>
  
  <p>My Context is only one in all application. I don't need derived class to pass context object, but i like to inject it in base class to using mocks for tests in future.</p>
  
  <p><strong>I Solve the problem:</strong></p>
  
  <p>Sorry, I'm confusing with the question, but i'm solving my problem building a Factory:</p>
  
  <pre><code>public abstract class BaseRepository&lt;TEntity&gt; : IBaseRepository&lt;TEntity&gt;
     where TEntity : class
  {
      private readonly ContextFactory _contextFactory = new ContextFactory();
  
      protected DatabaseContext CurrentContext
      {
          get
          {
              return this._contextFactory.GetCurrentContext();
          }
      }
   }
  </code></pre>
  
  <p>And my derived class will look like that:</p>
  
  <pre><code>public class UsuarioRepository : BaseRepository&lt;IUsuario&gt;, IUsuarioRepository
  {
  }
  </code></pre>
  
  <p>And My Factory like that:</p>
  
  <pre><code>public class ContextFactory
  {
      public DatabaseContext GetCurrentContext()
      {
          return new DatabaseContext();
      }
  }
  </code></pre>