首页 > 解决方案 > 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

标签: asp.net-core.net-coreasp.net-core-webapi

解决方案


不要在 HTTP 请求中运行长时间运行的任务,这些任务应该在单独的进程中完成,同时立即向客户端返回响应。

参考这个问题的答案

正如那里所建议的那样,您可以使用Hangfire 之类的东西来运行后台进程。

更新 注入 IServiceScopeFactory 不是一个好习惯。就像您正在实施服务定位器反模式一样。而是直接注入存储库,让 DI 找出解决方案和范围。


推荐阅读