asp.net-core - Autofac、线程和 IServiceScopeFactory
问题描述
我有一个问题:服务提供者在方法到达时被处理。这是一个问题还是我的错?
我的服务
public class BomService
{
private readonly IServiceScopeFactory _scope;
public BomService(IServiceScopeFactory scope)
{
_scope = scope;
}
public void ImportAsync(ImportRequestDto importSettings)
{
Task.Run(async () => await ImportFile.ImportAsync<Bom, CatalogContext>(_scope));
}
}
方法
public static async Task ImportAsync<T, TContext>(IServiceScopeFactory parentScope) where T : class where TContext : DbContext
{
using var scope = parentScope.CreateScope();
var repo = scope.ServiceProvider.GetService<IGenericRepository<T, TContext>>();
}
错误:
Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed
解决方案
不要在 HTTP 请求中运行长时间运行的任务,这些任务应该在单独的进程中完成,同时立即向客户端返回响应。
参考这个问题的答案
正如那里所建议的那样,您可以使用Hangfire 之类的东西来运行后台进程。
更新 注入 IServiceScopeFactory 不是一个好习惯。就像您正在实施服务定位器反模式一样。而是直接注入存储库,让 DI 找出解决方案和范围。
推荐阅读
- javascript - 连接 socket.io 时由于 xhr 轮询错误而出现 connect_error
- java - Multipart(一部分是 JSON,另一部分是二进制)数据在使用 Flux 读取时被截断
- autohotkey - 蓝牙键盘上的自动热键重新映射键(浏览器主页)不起作用
- javascript - 当前页面焦点样式未使用 javascript 正确设置,出了什么问题
- java - 我怎样才能摆脱日食中的自动替换?
- devextreme - DevExtreme:ASP.NET Core:dxTileView:以编程方式选择/聚焦磁贴
- java - 不能使用处理程序延迟启动片段
- sift - 在 VMware 工作站 16 pro 上下载 Sift 工作站时出现问题
- ssl - 存储在 SSL 配置 XML 中加密的 keyStorePassword 值
- react-native - 开玩笑无法编译流程(react-native)