I'm using AutoFac to inject a concrete data context in my web application. I want to execute the database context's SaveChanges()
method at the end of the request if there were no exceptions on the page. Otherwise I just want to dispose of the context as normal.
I noticed that AutoFac has an OnRelease
method. Intellisense for the method states:
Run a supplied action instead of disposing instances when they're no longer required.
As such, I was thinking of doing something like this:
builder.RegisterType<MyContext>().As<IDbContext>().InstancePerHttpRequest()
.OnRelease(x => {
if (HttpContext.Current != null && HttpContext.Current.Error == null)
x.SaveChanges();
if (x != null)
{
x.Dispose();
x = null;
}
});
Is this an appropriate place to commit changes for the data context? Is it guaranteed to run on every request, even when an Exception occurs?