I have a problem saving changes to my database using SaveChangesAsync inside a AKKA.NET receive function. Can someone explain what is going on?
Some more details: I have this receive block:
Receive<UpdateUnitVM>((msg) => {
using (var scope = AutofacDependencyContainer.Current.CreateTenantScope(new TenantId(msg.UnitConfiguration.TenantId)))
{
var db = scope.GetService<ApplicationDbContext>();
...work on some objects inside the db context
//now save and continue with next actor using PipeTo
var continueFlags = TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously;
db.SaveChangesAsync().ContinueWith(myint => new UnitConditionRuleGuard.UnitChanged(msg.UnitConfiguration.GetTenantUnitPair()), continueFlags).PipeTo(unitConditionRuleGuard);
}
});
If I change the code to use SaveChanges like this it works:
Receive<UpdateUnitVM>((msg) => {
using (var scope = AutofacDependencyContainer.Current.CreateTenantScope(new TenantId(msg.UnitConfiguration.TenantId)))
{
var db = scope.GetService<ApplicationDbContext>();
...work on some objects inside the db context
//now save (blocking) and continue with next actor sequentially
db.SaveChanges();
unitConditionRuleGuard.Tell(new UnitConditionRuleGuard.UnitChanged(msg.UnitConfiguration.GetTenantUnitPair()));
}
});
Be aware that the using-block creates a new Autofac dependency-injection container scope, so after the using block is exited, the db-object is disposed. I have a feeling that this is the problem. However, I'm not sure what to do about it and how to extend the lifetime of the dbcontext-object appropriately.