Skip to content

SavingChanges event not raised when using AddDbContextPool instead of AddDbContext. #24618

@TiagoOliveiraMarques

Description

@TiagoOliveiraMarques

File a bug

I'm trying to intercept calls to SaveChanges() and apply some custom logic. For that I'm registering an event handler to SavingChanges event in the DbContext constructor.

It all works nicely as long as I'm using IServiceCollection.AddDbContext method. If AddDbContextPool is used the event handler is registered the first time the DbContext is created but something seems to happen in between this and when SaveChanges is called, since then no handlers seem to be attached.

I can try create a full repro if needed.

Include your code

DbContext.cs:

public class MyDbContext : DbContext
    {
        protected MyDbContext (DbContextOptions<MyDbContext> options)
            : base(options)
        {
            SavingChanges += OnSavingChanges;
        }

        private void OnSavingChanges(object sender, SavingChangesEventArgs e)
        {
            // do stuff here.
        }
    }

Startup.cs (which doesn't work)

services.AddDbContextPool<MyDbContext>(options =>
  {
      options.UseSqlite(Configuration.GetConnectionString("Sqlite"));
  });

Startup.cs (which works)

services.AddDbContext<MyDbContext>(options =>
  {
      options.UseSqlite(Configuration.GetConnectionString("Sqlite"));
  });

Include stack traces

N/A

Include verbose output

N/A

Include provider and version information

EF Core version: 5.0.5
Database provider: Microsoft.EntityFrameworkCore.Sqlite
Target framework: 5.0.104
Operating system: Windows 10
IDE: Jetbrains Rider 2020.3.4

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions