I am trying to check if AppRoles exit in the database and if not create AppRoles as show below.
However, I got System.InvalidOperationException: ‘Cannot resolve scoped service ‘Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]’ from root provider.’ exception when i built the app
using (var serviceScope = app.Services.CreateScope()) {
var services = serviceScope.ServiceProvider;
var dbContext = services.GetRequiredService<AppDbContext>();
dbContext.Database.EnsureCreated();
var roleManager = app.Services.GetRequiredService<RoleManager<IdentityRole>>();
if (! await roleManager.RoleExistsAsync(AppRoles.User))
{
await roleManager.CreateAsync(new IdentityRole(AppRoles.User));
}
if (! await roleManager.RoleExistsAsync(AppRoles.Editor))
{
await roleManager.CreateAsync(new IdentityRole(AppRoles.Editor));
}
if (!await roleManager.RoleExistsAsync(AppRoles.Administrator))
{
await roleManager.CreateAsync(new IdentityRole(AppRoles.Administrator));
}
}
I expect the roles to created if the roles does not exit in the DB already
Abdulfatai Abdulrahman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.