Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager'

By FoxLearn 5/31/2024 9:44:33 AM   89
How to fix Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager' in ASP.NET Core.

If you got an error when running the app and accessing the Roles controller as shown below.

An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'BlogEngine.Controllers.RolesController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

The error message you're encountering typically occurs in ASP.NET Core applications when there's a missing service registration. In this case, it seems like you're trying to use RoleManager from Microsoft.AspNetCore.Identity but haven't registered it in your dependency injection container.

To resolve this issue, ensure that you've added the necessary services for ASP.NET Core Identity in your Startup.cs file's ConfigureServices method.

Here's an example of how you can do this:

public void ConfigureServices(IServiceCollection services)
{
    // Add ASP.NET Core Identity
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    
    // Other your service registrations
    
    services.AddControllersWithViews();
    services.AddRazorPages();
}

Ensure that you replace ApplicationUser and ApplicationDbContext with your custom user and context types if you've overridden them.

If you don't use custom user, you can add this row to Startup.cs file

services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

In your controler, you can use like this.

public class RolesController : Controller
{
    RoleManager<IdentityRole> _roleManager;
    UserManager<IdentityUser> _userManager;

    public RolesController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
    {
        _roleManager = roleManager;
        _userManager = userManager;
    }   
}

If you've already added the necessary services and still encounter the error, double-check your code where you're trying to use RoleManager to ensure there are no typos or other issues.