Skip to content

Proxies retain a reference to pooled DbContext after it is returned to the pool #25486

@ghost

Description

I've been using AddDbContextPool to inject an instance of my database into asp.net core controllers. In one instance, I also have a background task that runs via

services.AddHostedService<AppCode.SignalR.Daemon>();`

The Daemon implements IHostedService and IDisposable and retrieves IServiceScopeFactory in its constructor. A timer uses this to create a database context (with the scope correctly wrapped in a using statement) if it needs to update the database (it's monitoring which users are logged in and updating their session times if they log out). Through the day, the memory usage of the app slowly increases, butforcing periodic garbage collection helps to slow this a little. However, taking a memory dump shows that a lot of memory is being used by EntityFrameworkCore.Internal.LazyLoader at the very top of the flame graph.

RD28187824B03E_w3wp_29304 flameGraph1

Two entries below (on the line below LIB <<System.Private.CoreLib!List>> is a reference to DependencyInjection.ServiceLookup.ServiceProviderEngineScope and then further references to the database context pool (I'm using AddDbContextPool to inject the database)

The timer doesn't capture the database scope other than via ServiceProvider.GetRequiredService() so I can't see where this memory is being held onto, unless there's an issue with the lazyloader (although the code I'm accessing in the database doesn't reference any lazy loaded entities.

EF Core version: 5.0.8
Microsoft.EntityFrameworkCore.SqlServer
Target framework: NET 5.0
Operating system: Windows 10 (publishing to Azure web app)
IDE: Visual Studio 2019 16.9.5

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions