Resolving type with PerRequestLifetimeManager without HTTP request

好久不见. 提交于 2019-11-27 14:51:54

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!