Error Message :A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of 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;
}
}
In above service FindByIdAsync throwing this exeption
while i am debugging step by step then i am not facing this error
my setup in startup file as below
services.AddTransient<IAuthService, AuthService>();
Even i changed above service method but its not working why it requires more time to perform or there is any another issue?
Edit
these manager are passed in service
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
this is ctor
public AuthService(UserManager<ApplicationUser> _userManager,
RoleManager<ApplicationRole> _roleManager,
IConfiguration configuration) : base(configuration)
{
this._userManager = _userManager;
this._roleManager = _roleManager;
}
User manage and role manager are used from Microsoft.AspNetCore.Identity
services.AddDbContext<Db>(options =>
{
options.UseSqlServer(mySqlConnectionStr);
}
);
CodePudding user response:
The DbContext has a scoped service lifetime, coupled to an asp.net request. Thus services using the context should preferably also have a scoped service lifetime.
CodePudding user response:
I can recommend you such approach (TModel can be yours 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);
}