K. Akins
K. Akins

Reputation: 737

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

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?

Upvotes: 0

Views: 3185

Answers (1)

davidfowl
davidfowl

Reputation: 38764

The official documentation has examples on how to use scoped services within a hostes service https://learn.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.

Upvotes: 2

Related Questions