Home > Blockchain >  Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[x.AppUser]'
Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[x.AppUser]'

Time:11-08

I got this error message when I try to get all users from database Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[xxx.Models.ApplicationUser]' while attempting to activate 'xxx.Areas.RegisteredUser.Controllers.AdminUserSetController'. here is the code

AdminUserSetController.cs

public class AdminUserSetController : Controller
    {
        private UserManager<ApplicationUser> userManager;
        private IPasswordHasher<ApplicationUser> passwordHasher;

        public AdminUserSetController(UserManager<ApplicationUser> usrMgr, IPasswordHasher<ApplicationUser> passwordHash)  // <--- i think the problem is here
        {
            userManager = usrMgr;
            passwordHasher = passwordHash;
        }

        public IActionResult Index()     //<------ does not hit when load  
        {
            return View(userManager.Users);
        }

program.cs

builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
    builder.Configuration.GetConnectionString("LifeConnection")
    ));


builder.Services.Configure<StripeSettings>(builder.Configuration.GetSection("Stripe"));
builder.Services
    .AddIdentity<IdentityUser, IdentityRole>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddScoped<iUnitOfWork, UnitOfWork>();
builder.Services.AddSingleton<IEmailSender, EmailSender>();
builder.Services.AddRazorPages();
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = $"/Identity/Account/Login";
    options.LogoutPath = $"/Identity/Account/Logout";
    options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseDeveloperExceptionPage();
app.UseRouting();
StripeConfiguration.ApiKey = builder.Configuration.GetSection("Stripe:SecretKey").Get<string>();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();

app.MapControllerRoute(
    name: "default",
    pattern: "{area=UnRegUser}/{controller=Home}/{action=Index}/{id?}");

app.Run();

ApplicationUser.cs

public class ApplicationUser : IdentityUser
    {
        [Required]
        public string FullName { get; set; }
        public string? UserType { get; set; }

        public bool? Active { get; set; } = true;

        public int? CompanyId { get; set; }

        [ForeignKey ("CompanyId")]
        [ValidateNever]
        public Company Company { get; set; }
    }

ApplicationDBContext.cs

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

        }

        
        
        public DbSet<ApplicationUser> ApplicationUsers { get; set; }
        public DbSet<Company> Companies { get; set; }

    }

public AdminUserSetController(UserManager usrMgr, IPasswordHasher passwordHash) I think the problem is here. but I dunno how to do. please help

CodePudding user response:

Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[xxx.Models.ApplicationUser]' while attempting to activate 'xxx.Areas.RegisteredUser.Controllers.AdminUserSetController'.

From the error message we can see the problem, in your AdminUserSetController, you use ApplicationUser

private UserManager<ApplicationUser> userManager;
private IPasswordHasher<ApplicationUser> passwordHasher;

But in Program.cs, you register IdentityUser

builder.Services
    .AddIdentity<IdentityUser, IdentityRole>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

You need to change code like :

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

And make some change to your context:

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

        }

Read Custom user data to know more.

  • Related