Time to time I would get the following error and am trying to understand better as to why it happens.
I am seeding users in my configure section and I have the following code.
private WarehouseDBContext _context;
public SeedUsers(WarehouseDBContext context)
{
_context = context;
}
public async void SeedAdminUser(IApplicationBuilder app, RoleManager<IdentityRole>
roleManager, UserManager<ApplicationUser> userMrg)
{
var user = new ApplicationUser
{
UserName = "test@outlook.com",
NormalizedUserName = "test@outlook.com",
Email = "test@outlook.com",
NormalizedEmail = "test@outlook.com",
FirstName = "test",
LastName = "user",
EmailConfirmed = true,
LockoutEnabled = false,
SecurityStamp = Guid.NewGuid().ToString()
};
var password = new PasswordHasher<ApplicationUser>();
var hashed = password.HashPassword(user, "test123453!");
user.PasswordHash = hashed;
var userStore = new UserStore<ApplicationUser>(_context);
await userStore.CreateAsync(user);
await userStore.AddToRoleAsync(user, "admin");
var result =await userMrg.AddToRoleAsync(user, "admin");
}
This is how I consume the function i shortend the code so didnt have to read all my configure.
public async void Configure(IApplicationBuilder app, IWebHostEnvironment env,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager, SeedUsers seed)
{
seed.SeedRoles();
seed.SeedAdminUser(app,roleManager, userManager);
seed.SeedClaimsForSuperAdminAsync(app, roleManager, userManager);
}
I have declared it as such in the startup.cs
services.AddTransient<SeedUsers>();
services.AddTransient<WarehouseDBContext>();
The user is indead added to the user store but the code fails on the userMgr which is being passed in from the startup.cs as such and the AddToRoleAsync fails and does not insert it into the table their is no message that it fails just this error.
So why then am I getting the error. It happens every time on the line above await userStore.CreateAsync(user);?
System.InvalidOperationException: 'A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see