title: How to fix 'A second operation started on this context before a previous operation completed...' when working with dependency injection?
body: <p>when reading data from the database I get this error:</p>
  
  <blockquote>
    <p>A second operation started on this context before a previous operation
    completed. Any instance members are not guaranteed to be thread safe.</p>
  </blockquote>
  
  <p>I have the following ApplicationContext.cs:</p>
  
  <pre><code>public class ApplicationContext : Microsoft.EntityFrameworkCore.DbContext
  {
      public ApplicationContext(DbContextOptions&lt;ApplicationContext&gt; options)
          : base(options)
      { }
  
      public DbSet&lt;MyClass&gt; MyClasses{ get; set; }
  }   
  </code></pre>
  
  <p>The following ApplicationContextFactory.cs</p>
  
  <pre><code>public class ApplicationContextFactory : IDesignTimeDbContextFactory&lt;ApplicationContext&gt;
  {
      public ApplicationContext CreateDbContext(string[] args)
      {
          var builder = new DbContextOptionsBuilder&lt;ApplicationContext&gt;();
          var connection = "myConnectionString";
  
          builder.UseSqlServer(connection);
  
          return new ApplicationContext(builder.Options);
      }
  }   
  </code></pre>
  
  <p>The following ServiceLoader.cs (where I declare the DI):</p>
  
  <pre><code>public static class ServiceLoader
  {
      public static void ConfigureServices(IServiceCollection services)
      {
          services.AddSingleton&lt;IRepository, Repository&gt;();
  
          var connection = "myConnectionString";
          services.AddDbContext&lt;ApplicationContext&gt;(options =&gt; options.UseSqlServer(connection));
      }
  }
  </code></pre>
  
  <p>and finally, the following Repository, where the exception is thrown:</p>
  
  <pre><code>public class Repository : IRepository
  {
      private ApplicationContext _db;
  
      public Repository (ApplicationContext db)
      {
          _db = db;
      }
  
      public List&lt;MyClass&gt; Get()
      {
          _db.MyClasses.ToList();
      }
  }
  </code></pre>
  
  <p>I have also tried to declare the Repository as Transient instead of Singleton, but a similar error is thrown</p>
  
  <blockquote>
    <p>'An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.'</p>
  </blockquote>
  
  <p>Any idea on how to fix this? Thanks!</p>