Aspnet Core DI + EF: "The connection was not closed. The connection's current state is connecting"

asp.net-core c# dependency-injection entity-framework-core

Question

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?

1
0
6/27/2018 3:44:44 PM

Accepted Answer

The official documentation has examples on how to use scoped services within a hostes service https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1#consuming-a-scoped-service-in-a-background-task.

TL;DR You inject the IServiceProvider (which is always available) into your IHostedService implementation, then create a scope per invocation and resolve the DbContext from there.

2
6/30/2018 9:00:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow