I have moved away from using PerRequestLifetimeManager
for this very issue. I have now started using HierarchicalLifetimeManager
with container hierarchies instead and then you need to set up your app to create a new child container per intended scope (such as a request or a job) and dispose that child container when that scope is complete.
There are some libraries that hook into MVC and WebAPI to create a new child container per request. A quick search found this one for MVC: Unity.Mvc5 and the official Unity.AspNet.WebApi NuGet package includes a UnityHierarchicalDependencyResolver
.
To get this to work with your task app, you will have to roll your own method to create a child container to control your scope, but that is pretty easy. Just call IUnityContainer childContainer = container.CreateChildContainer()
, resolve your instances using the child container and do your work and then at the end of your scope call childContainer.Dispose()
.