title: Injecting Dependency programmatically asp.net core
body: <p>I'm just starting with <code>Asp.net core</code> <em>Dependency Injection</em>, and my concept could be inaccurate. <a href="https://docs.asp.net/en/latest/mvc/controllers/dependency-injection.html" rel="nofollow noreferrer">This docs.asp.net post</a> explains how to inject context to a controller. I have little confusion regarding injection, in testing perspective. Assume we have following scenario:</p>
  <pre><code>public interface ITasksRepository
  { 
     public void Create();
  }
  
  //This is fake implementation, using fake DbContext for testing purpose
  public class TasksRepositoryFake : ITasksRepository
  {
     public void Create()
     {
       FakeDbContext.Add(sometask);
       //logic;
     }
  }
  
  //This is actual implementation, using actual DbContext
  public class TasksRepository : ITasksRepository
  {
     public void Create()
     {
       DbContext.Add(someTask);
       //logic;
     }
  }
  </code></pre>
  <p>Now in order to inject context in controller, we design it as:</p>
  <pre><code>public class TasksController : Controller
  {
      public ITasksRepository TaskItems { get; set; }
  
      public TodoController(ITaskRepository taskItems)
      {
          TaskItems = taskItems;
      }
      //other logic
   }
  </code></pre>
  <p>What asp.net <code>core</code> provides as builtin feature is, we can register the dependency injection in startup class as follows:</p>
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      // Add framework services.
      services.AddMvc();
      services.AddSingleton&lt;ITasksRepository, TasksRepositoryFake&gt;();
  }
  </code></pre>
  <p>According to this logic, my <code>TaskRepositoryFake</code> will be injected to the controller. So far, everything is clear. My questions/confusions regarding this are as follows:</p>
  <p><strong>Questions:</strong></p>
  <ul>
  <li>How can I use this builtin DI feature to inject the context using some logic? May be programatically, or configuration based, or environment based? <em>(for example, always inject fake context, when using 'test' environment? etc.)</em></li>
  <li>Is it even possible? If we always have to change this manually in <em>StartUp</em> class, then how does this builtin DI feature serve us? Because we could have simply done that in controller, without this feature.</li>
  </ul>