Question: How do you inject RoleManager in Asp.Net 6 Dependency Injection Container, when I do am getting an error below "InvalidOperationException: Cannot consume scoped service 'Microsoft-AspNetCore-Identity-IRoleStore`1[Microsoft-AspNetCore-Identity-dentityRole]' from singleton 'Microsoft-AspNetCore.Identity-RoleManager`1[Microsoft-AspNetCore-Identity-IdentityRole]'."
Please Login to see the rest of the answer
using (RoleManager<IdentityRole> roleManager = _serviceProvider.GetRequiredService<RoleManager<Microsoft.AspNetCore.Identity.IdentityRole>>()
)
{
foreach (string roleName in roleNames)
{
try //This try and catch is only used on development to see the error
{
bool roleExist = await roleManager.RoleExistsAsync(roleName).ConfigureAwait(false);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await roleManager.CreateAsync(new IdentityRole(roleName)).ConfigureAwait(false);
}
}
catch (Exception ex) //Catch the error only in development
{
}
}
}
If you have a problem understanding this solution, leave a comment below or contact us so we can help you.
Dave, I think you need to log out and try to log in again for the Roles to be effective. Let us know what you find.
Why is the User no getting Assigned to the Role? I have implemented the code above and when checking to see if the User is in the Role the code is not effective. Anything am missing?