title: Singleton with DbContext - creating instance in Startup.cs
body: <p>I am using ASP.net core. I have problem with implementing dbcontext into singleton.</p>
  
  <p>I need my singleton IModuleRepository to be running right after start of the project. So I am creating new instance of this dependency in <code>public void ConfigureServices(IServiceCollection services)</code> in <code>Startup.cs</code> file.</p>
  
  <p>This singleton is using another singleton, so I am using it like this:</p>
  
  <pre><code>services.AddDbContext&lt;ModulesDbContext&gt;(options =&gt;
  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).EnableSensitiveDataLogging());
  ...    
  services.AddSingleton&lt;IModuleRepository, ModuleRepository&gt;();
  services.AddSingleton&lt;ICommunicationRepository&gt;(new CommunicationRepository(services.BuildServiceProvider().GetService&lt;IModuleRepository&gt;()));
  </code></pre>
  
  <p>In ModuleRepository I am using DBcontext.</p>
  
  <pre><code>// Db context
      private readonly ModulesDbContext _modulesDbContext;
  
      public ModuleRepository(ModulesDbContext modulesDbContext)
      {
          _modulesDbContext = modulesDbContext;
      }
  </code></pre>
  
  <p>When I am calling <code>_modulesDbContext.SomeModel.ToList();</code> I get error: </p>
  
  <blockquote>
    <p>System.InvalidOperationException: 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.</p>
  </blockquote>
  
  <p>How to avoid this error when I need this singleton to run after the project is started?</p>
  
  <p>Thank you for your help.</p>