Using Autofac in ASP.NET along with the ContainerDisposalModule, how can i support fire and forget calls that have component dependencies that need to be resolved? The problem I'm running into is that the ASP.NET request completes and disposes the lifetime scope of the request before the Task is ran, so any components that need to be resolved in the new thread fail with the message "Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed". What's the best way to support fire and forget call using Autofac in ASP.NET? I don't want to delay the request to perform certain tasks which can be done on background threads.
相关问题
- Carriage Return (ASCII chr 13) is missing from tex
- How to store image outside of the website's ro
- 'System.Threading.ThreadAbortException' in
- Request.PathInfo issues and XSS attacks
- How to dynamically load partial view Via jquery aj
相关文章
- asp.net HiddenField控件扩展问题
- asp.net HiddenField控件扩展问题
- Asp.Net网站无法写入错误日志,测试站点可以,正是站点不行
- asp.net mvc 重定向到vue hash字符串丢失
- FormsAuthenticationTicket expires too soon
- “Dynamic operations can only be performed in homog
- What is the best way to create a lock from a web a
- Add to htmlAttributes for custom ActionLink helper
Answer posted by Alex adapted to current Autofac and MVC versions:
InstancePerRequest
for a database contextILifetimeScope
as dependency to get to the containerSingleInstance
ensures it's the root lifetime scopeHostingEnvironment.QueueBackgroundWorkItem
to reliably run something in the backgroundMatchingScopeLifetimeTags.RequestLifetimeScopeTag
to avoid having to know the tagname autofac uses for PerRequest lifetimeshttps://groups.google.com/forum/#!topic/autofac/gJYDDls981A https://groups.google.com/forum/#!topic/autofac/yGQWjVbPYGM
Gist: https://gist.github.com/janv8000/35e6250c8efc00288d21
Global.asax.cs:
AsyncRunner.cs
Controller
ListingService
You need to create a new lifetime scope that is independent of the request lifetime scope. The blog post below shows an example of how to do this using MVC but the same concept can be applied to WebForms.
http://aboutcode.net/2010/11/01/start-background-tasks-from-mvc-actions-using-autofac.html
If you need to ensure that the async work is definitely performed after the request is finished then this is not a good approach. In such cases I would recommend posting a message onto a queue during the request allowing a separate process to pick it up and perform the work.