[英]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.