How to fix "InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager'"

By FoxLearn 5/11/2024 3:25:05 AM   806
This post shows you How to solve "InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager [Microsoft.AspNetCore.Identity.IdentityUser]' has been registered." when custom ASP.NET Core Identity.

The "InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager'" error typically occurs when the ASP.NET Core application is trying to use the UserManager service but it hasn't been registered in the dependency injection container.

For example if you create a custom user class as shown below.

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Make sure that you have correctly registered the UserManager service in your application's Startup.cs file, particularly in the ConfigureServices method.

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

You need to replace ApplicationUser with your user model and ApplicationDbContext with your application's DbContext.

Ensure that you have imported the necessary namespaces at the top of your files where UserManager is being used.

using Microsoft.AspNetCore.Identity;

Verify Injection of UserManager and ensure that you are injecting UserManager properly where it's being used.

private readonly UserManager<ApplicationUser> _userManager;

public MyController(UserManager<ApplicationUser> userManager)
{
    _userManager = userManager;
}

You need to open the _LoginPartial.cshtml file

@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

Next, change to

@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

You also need to open all related files and then change IdentityUser to ApplicationUser.

Check the DbContext Configuration and ensure that your DbContext is configured correctly to work with Identity.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

By following these steps, you should be able to fix the "InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager'" error in your ASP.NET Core application.