I'm using EF Core, in an ASP.NET Core environment. My context is registered in my DI container as per-request.
I need to perform extra work before the context's SaveChanges()
or SaveChangesAsync()
, such as validation, auditing, dispatching notifications, etc. Some of that work is sync, and some is async.
So I want to raise a sync or async event to allow listeners do extra work, block until they are done (!), and then call the DbContext
base class to actually save.
public class MyContext : DbContext
{
// sync: ------------------------------
// define sync event handler
public event EventHandler<EventArgs> SavingChanges;
// sync save
public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
// raise event for sync handlers to do work BEFORE the save
var handler = SavingChanges;
if (handler != null)
handler(this, EventArgs.Empty);
// all work done, now save
return base.SaveChanges(acceptAllChangesOnSuccess);
}
// async: ------------------------------
// define async event handler
//public event /* ??? */ SavingChangesAsync;
// async save
public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
// raise event for async handlers to do work BEFORE the save (block until they are done!)
//await ???
// all work done, now save
return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
}
As you can see, it's easy for SaveChanges()
, but how do I do it for SaveChangesAsync()
?