Search code examples
c#asp.net-coreef-core-3.0

ASP.NET Core AddDbContextPool not firing ChangeTracker events


I have a ASP.NET Core 3.0 application using .NET Core 3.0 and EF Core 3.0. I am using AddDbContextPool to register my DbContext:

services.AddDbContextPool<IMyDbContext, MyDbContext>(
            optionsAction: options => options.UseSqlServer(
                connectionString: Configuration.GetConnectionString("MyDatabase"))
        );

In my DbContext constructor, I attach to two events of the ChangeTracker:

public MyDbContext(DbContextOptions<MyDbContext> options)
            : base(options)
        {
            // Attach to our important events
            ChangeTracker.StateChanged += ChangeTracker_StateChanged;
            ChangeTracker.Tracked += ChangeTracker_Tracked;
        }

The first time I run the application the events are fired when I add items to my context. Once the page is done loading I make another request but none of my events fire this time when adding items to my context. It seems when it pulls a context out of the pool it no longer has the event handlers registered.

I have no issues when I use regular AddDbContext. Is this expected behavior or is there a different way I should register my event handlers?


Solution

  • This should probably be considered a bug--can you file it at https://github.com/aspnet/EntityFrameworkCore/issues

    The context instance should be reset to the state it was in after it was constructed. However, this may be tricky for the events.

    The best way forward is to not AddDbContextPool. For most scenarios the difference in perf over using AddEbContext is negligible.