Home > Articles > Details

Cannot consume scoped service Microsoft.AspNetCore.Identity.IRoleStore from singleton 'Microsoft.AspNetCore.Identity.RoleManager


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]'."

Login to See the Rest of the Answer

Answer: The problem here is that you are trying to inject an interface that Asp.Net Framework has already registered in the Dependency Injection. It is like injecting IConfiguration Interface into the DI, this interface already comes injected into DI. 

In order to resolve RoleManager Error in Asp.Net Core, you need to obtain the Service via ServiceProvider Interface and wrap it in a using block, see the code below:

  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.

 


If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

Merry said:

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.

Posted On: February 23, 2022 14:53:16 PM
Dave said:

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?

Posted On: February 23, 2022 14:52:37 PM

© 2022 - ErnesTech - Privacy