在ASP.NET中使用Autofac以及ContainerDisposalModule,我如何支持fire和forget具有需要解析的组件依赖性的调用?我遇到的问题是ASP.NET请求在Task运行之前完成并处理请求的生命周期范围,因此任何需要在新线程中解析的组件都会失败,并显示消息“实例无法解析并且无法从此LifetimeScope创建嵌套生命周期,因为它已经被处理掉了“。在ASP.NET中使用Autofac支持fire和忘记调用的最佳方法是什么?我不想延迟执行某些可以在后台线程上完成的任务的请求。
答案 0 :(得分:4)
Alex发布的答案改编为当前的Autofac和MVC版本:
InstancePerRequest
用于数据库上下文ILifetimeScope
作为依赖项添加到容器SingleInstance
确保它是根生存期范围HostingEnvironment.QueueBackgroundWorkItem
可靠在后台运行MatchingScopeLifetimeTags.RequestLifetimeScopeTag
以避免必须知道autofac用于PerRequest有效期的标记名https://groups.google.com/forum/#!topic/autofac/gJYDDls981A https://groups.google.com/forum/#!topic/autofac/yGQWjVbPYGM
要点:https://gist.github.com/janv8000/35e6250c8efc00288d21
的Global.asax.cs:
protected void Application_Start() {
//Other registrations
builder.RegisterType<ListingService>();
builder.RegisterType<WebsiteContext>().As<IWebsiteContext>().InstancePerRequest(); //WebsiteContext is a EF DbContext
builder.RegisterType<AsyncRunner>().As<IAsyncRunner>().SingleInstance();
}
AsyncRunner.cs
public interface IAsyncRunner
{
void Run<T>(Action<T> action);
}
public class AsyncRunner : IAsyncRunner
{
public ILifetimeScope LifetimeScope { get; set; }
public AsyncRunner(ILifetimeScope lifetimeScope)
{
Guard.NotNull(() => lifetimeScope, lifetimeScope);
LifetimeScope = lifetimeScope;
}
public void Run<T>(Action<T> action)
{
HostingEnvironment.QueueBackgroundWorkItem(ct =>
{
// Create a nested container which will use the same dependency
// registrations as set for HTTP request scopes.
using (var container = LifetimeScope.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
{
var service = container.Resolve<T>();
action(service);
}
});
}
}
控制器
public Controller(IAsyncRunner asyncRunner)
{
Guard.NotNull(() => asyncRunner, asyncRunner);
AsyncRunner = asyncRunner;
}
public ActionResult Index()
{
//Snip
AsyncRunner.Run<ListingService>(listingService => listingService.RenderListing(listingGenerationArguments, Thread.CurrentThread.CurrentCulture));
//Snip
}
ListingService
public class ListingService : IListingService
{
public ListingService(IWebsiteContext context)
{
Guard.NotNull(() => context, context);
Context = context;
}
}
答案 1 :(得分:2)
您需要创建一个独立于请求生命周期范围的新生命周期范围。下面的博客文章展示了如何使用MVC执行此操作的示例,但同样的概念可以应用于WebForms。
http://aboutcode.net/2010/11/01/start-background-tasks-from-mvc-actions-using-autofac.html
如果您需要确保在请求完成后明确执行异步工作,那么这不是一个好方法。在这种情况下,我建议在请求期间将消息发布到队列中,允许单独的进程获取它并执行工作。