Spent several hours on this, thought I would share.
Using Unity something along the way I read suggested using HierarchicalLifetimeManager for asp webapi.
container.RegisterType<IDataContext, ApiContext>(new HierarchicalLifetimeManager());
container.RegisterType<IDataContextAsync, ApiContext>(new HierarchicalLifetimeManager());
container.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new HierarchicalLifetimeManager());
First update with asp.net webapi2 controller works fine, then the Dispose override is called and any further api calls give this error: The operation cannot be completed because the DbContext has been disposed
Solved by switching to PerResolveLifetimeManager. Not sure if this is the most proper one to use, but I am able to make multiple calls now.
container.RegisterType<IDataContext, ApiContext>(new PerResolveLifetimeManager());
container.RegisterType<IDataContextAsync, ApiContext>(new PerResolveLifetimeManager());
container.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerResolveLifetimeManager());
Feb 24, 2016 at 5:01 AM
Edited Feb 24, 2016 at 7:56 PM
PerResolve is def the appropriate one to use for a web api or page. It is basically behaves as a "singleton" for the lifetime of the object in which it was created (until its disposed). In the case of the web request, this is usually just whatever
you injected into your controllers, which is disposed after each call to the controller is finished.
A HierarchicalLifeTimeManager also behaves as a singleton as well but in the context of the unity container or scoped child container in which it was created.
Hard to say without seeing the rest of the code, but in your case, because it looks like you registered them on the same container, I suspect that those instances were disposed and never created again because they were basically registered as singletons in
that container but disposed, and you never re-created the container. I think if you created a new instance of an actual child container with every call and resolved it you might get a similar effect as the PerResolveLifeTimeManager. In either case, I still
think per resolve is the more appropriate one to use in this case.
Of course I could be completely off base here, but it seems logical to me! :)