I would like to put in a bit of infrastructure on my project to SaveChanges
on my db context at the end of every request.
So I create a simple piece of Owin middleware
app.Use(async (ctx, req) => {
await req();
var db = DependencyResolver.Current.GetService<MyDbContext>();
await db.SaveChangesAsync();
});
This does not work and throws the error
Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.
If I resolve the db before completing the request
app.Use(async (ctx, req) => {
var db = DependencyResolver.Current.GetService<MyDbContext>();
await req();
await db.SaveChangesAsync();
});
It doesn't throw an error but it also doesn't work (as in changes aren't saved to the db and viewing db in the debugger shows the DbSet
's Local
property throwing an InvalidOperationException
about it being disposed.
I've tried with and without async, registering the middleware before and after autofac configuration (app.UseAutofacMiddleware(container)
) and resolving the LifetimeScope
directly from the Owin environment. All give me the same results.
I've done something like this before with Structuremap, but can't seem to figure the correct way to get Autofac to play nice.