LiXiang98

导航

 

比如一个方法里面是一个Task,且没有await,方法运行结束,当前Scope就释放了,此时就需要创建一个独立于当前请求的scope。

在遇到lifetime的一些其他错误的时候也可以试试使用ServiceScopeFactory。

public class Test
{
  private readonly IServiceScopeFactory serviceScopeFactory;
  public Test(IServiceScopeFactory serviceScopeFactory)
  {
       this.serviceScopeFactory = serviceScopeFactory;
  }  
   public Task TestMeathd(string str)
    {
      return Task.Run(_=>{
        using var scope = serviceScopeFactory.CreateScope();
         var xxx =scope.ServiceProvider.GetRequiredService<xxx>();
        xxx.dosomething();
     });
    }
}            

 

posted on 2022-10-09 10:06  LiXiang98  阅读(52)  评论(0)    收藏  举报