繁体   English   中英

我在 asp.net 核心中的 asp.net 核心标识中面临与线程相关的问题?

[英]I am facing issue thread related issue in asp.net core identity in asp.net core?

错误消息:在前一个操作完成之前,在此上下文上启动了第二个操作。 这通常是由使用相同 DbContext 实例的不同线程引起的

 public async Task<UserSearchDto> GetSingle(string userId, string baseUrl)
        {
            
            var user =await  _userManager.FindByIdAsync(userId);
            if (user != null)
            {
                UserSearchDto userSearches = new UserSearchDto
                {
                    data
                };
                return userSearches;
            }
        }


在上面的服务 FindByIdAsync 中抛出这个异常

当我逐步调试时,我没有遇到此错误

我在启动文件中的设置如下

services.AddTransient<IAuthService, AuthService>();

即使我更改了上述服务方法,但它不起作用,为什么它需要更多时间来执行或还有其他问题?

编辑

这些经理在服务中通过


 private readonly UserManager<ApplicationUser> _userManager;
 private readonly RoleManager<ApplicationRole> _roleManager;

这是 ctor

public AuthService(UserManager<ApplicationUser> _userManager,
            RoleManager<ApplicationRole> _roleManager,
            IConfiguration configuration) : base(configuration)
        {
            this._userManager = _userManager;
            this._roleManager = _roleManager;
        }

从 Microsoft.AspNetCore.Identity 使用用户管理和角色管理器

 services.AddDbContext<Db>(options =>
            {
                options.UseSqlServer(mySqlConnectionStr);
            }
            );

DbContext 具有范围服务生命周期,与 asp.net 请求耦合。 因此使用上下文的服务最好也应该有一个范围服务生命周期。

我可以向您推荐这种方法(TModel 可以是您的 UserSearchDto):

    // Or your db context directly in class but this is better
    private readonly IServiceScopeFactory _factory;
    
    public async Task<TModel> FindByIdAsync(ulong id)
    {
         using var scope = _factory.CreateScope();
         // your context gets here
         await using var userManager = scope.ServiceProvider.GetRequiredService<UserManagerContext>();
         // this is important
         var entities = userManager.Set<TModel>().AsNoTracking();
         // data should be filled after FindByIdAsync(ulong id), not in this method
         return await entities.FirstOrDefaultAsync(t => t.Id == id);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM