gpt4 book ai didi

asp.net - 解析 ASP.NET 后台任务中的 Autofac 组件

转载 作者:行者123 更新时间:2023-12-02 10:16:35 24 4
gpt4 key购买 nike

在 ASP.NET 中使用 Autofac 以及 ContainerDisposalModule,我如何支持具有需要解决的组件依赖性的即发即忘调用?我遇到的问题是 ASP.NET 请求在运行任务之前完成并处理请求的生命周期范围,因此需要在新线程中解析的任何组件都会失败,并显示消息“实例无法解析”并且无法从此 LifetimeScope 创建嵌套生命周期,因为它已被释放”。在 ASP.NET 中使用 Autofac 支持即发即忘调用的最佳方式是什么?我不想延迟执行某些可以在后台线程上完成的任务的请求。

最佳答案

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);
}
});
}
}

Controller

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
}

列表服务

public class ListingService : IListingService
{
public ListingService(IWebsiteContext context)
{
Guard.NotNull(() => context, context);
Context = context;
}
}

关于asp.net - 解析 ASP.NET 后台任务中的 Autofac 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11910514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com