This is related to the following, but it is not exactly the same: EF. The connection was not closed. The connection's current state is connecting
I understand this error can be the result of a race condition when dealing with DbContext.
Here is a simplified example of what was causing me problems, and my solution to fix it. I just don't quite understand why my solution works:
Startup.cs
services.AddDbContext<MyDbContext>(options => options.UseSqlServer("ConnString"));
// This will cause the "Connection was not closed..." error.
services.AddSingleton<IHostedService, SomeBackgroundService>(provider =>
new SomeBackgroundService(provider.GetRequiredService<MyDbContext>());
// Instead, I instantiate the DbContext here instead of letting DI do it
// and this eliminates the error.
services.AddSingleton<IHostedService, SomeBackgroundService(provider =>
new SomeBackgroundService(new MyDbContext(
new DbContextOptionsBuilder<MyDbContext>().UseSqlServer("ConnString").Options));
Inside of my SomeBackgroundService
I execute some asynchronous queries, while at the same time other queries are being executed inside controller methods.
However, that being the case, shouldn't using provider.GetRequiredService<T>
instantiate a new DbContext in the same way?