EntityFrameworkCore - Diagnostics "Connection was not closed. The current state of the connection is open."

We seem to have done something to introduce some kind of threading problem into our application. This is a dotnet core 1.1.2 application using EntityFrameworkCore. With interruptions, but reproducibly, we get one of the following errors:

System.InvalidOperationException: "The connection was not closed. The status of the current connection is open. An exception was raised when an EF request was run.

or

System.InvalidCastException: "Cannot apply an object of type" System.Data.ProviderBase.DbConnectionClosedConnecting "to enter" System.Data.SqlClient.SqlInternalConnectionTds ".

or

System.ObjectDisposedException: "Unable to access the remote object. A common cause of this error is to remove the context that was allowed from the dependency injection, and then try to use the same context instance in another place in your application. This can happen if you call Dispose () in the context or wrap the context in the using statement. If you use dependency injection, you must let the dependency injection container take care of disposing of the context instances. '

This can happen at almost any point in the application, but this method seems to be the most common culprit (this is called more often):

public class WidgetConfigurationRepository : IWidgetConfigurationRepository
{

    public WidgetConfigurationRepository(LocalContext dataContext)
    {
        Context = dataContext ?? throw new ArgumentNullException(nameof(dataContext));
    }

    private LocalContext _context { get; private set; }

    public async Task<WidgetConfiguration> LoadConfigurationAsync(Guid widgetId)
    {
        return await _context.WidgetConfigurations
            .Include(x => x.Options)
            .FirstOrDefaultAsync(x => x.WidgetId.Equals(widgetId));
    }
...
}

The repository is created through the Core DI container and entered at runtime:

services.AddScoped<IWidgetConfigurationRepository, WidgetConfigurationRepository>();

LocalContext Scoped, Singleton LocalContext.

( ) , async await ed, , , , async await.

LocalContext LocalDbContextFactory, . , LocalContext. , .

, , , , , , .

, - Roslyn, , Task Task<T>, , - , , - , , , .

: EF. .

  • , IUserService "scope", (userManager, dbContext)
  • IServiceProvider, - " ". HttpContext.RequestServices .
  • , "" . , "" dbContext "".
  • JwtMessageHandler . _userService ( IUserService _userService). OnMessageReceived (var _userService =...).

, , .

ServiceProvider.GetService<>() , , .

, async await, , , , .

+4

Source: https://habr.com/ru/post/1688229/


All Articles