Reputation: 2866
Using ASP.NET Core 2.
I am trying to init some application-wide data. For that I created a new class called DbInitializer
, an interface called IDbInitializer
, and registered them with AddScoped
in Startup.ConfigureServices
.
Then from Startup.Configure
, I call DbInitializer.Initialize()
and inside that method there are a few calls to UserManager
:
if (appDbContext.Roles.All(i => i.Name != adminGroupName))
{
await roleManager.CreateAsync(new IdentityRole(adminGroupName));
};
var role = appDbContext.Roles.First(i => i.Name == adminGroupName);
if (appDbContext.Users.All(i => i.UserName != adminSettings.Username))
{
await userManager.CreateAsync(new ApplicationUser { UserName = adminSettings.Username,
Email = adminSettings.Username,
FirstName = adminSettings.FirstName,
LastName = adminSettings.LastName,
EmailConfirmed = true }, adminSettings.Password);
}
var adminUser = appDbContext.Users.First(i => i.UserName == adminSettings.Username);
if (!appDbContext.UserRoles.Any(i => i.RoleId == role.Id && i.UserId == adminUser.Id))
{
await userManager.AddToRoleAsync(adminUser, role.Name);
}
The problem is that I am getting, at random the exception
Cannot access a disposed object
from userManager.CreateAsync
or userManager.AddToRoleAsync
.
Upvotes: 2
Views: 3178
Reputation: 924
I believe the problem is that your DbInitializer.Initialize()
method call (which should be marked async
and return a Task
) is not properly being awaited, since the Startup.Configure
method must return void. It should work if you change your call to be DbInitializer.Initialize().Wait()
which will wait for the task to complete.
Upvotes: 6