Search code examples
asp.net-core-mvcasp.net-core-identity

Adding custom field to identity gives error Unable to resolve service for type IdentityUser while attempting to active Loginmodel


I have been trying to add a custom field in my Identity profile. The field is created in Database. But when I try to access the loginpage I get this error:

Error:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'MyProject.Areas.Identity.Pages.Account.LoginModel'.

startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DB_A66C9B_cemmecContext>(optionsBuilder => optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            

            //ORIGINAL
            //services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            //   .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            // Replace ApplicationUser with your concrete user class
            .AddSignInManager<SignInManager<ApplicationUser>>()
            .AddDefaultTokenProviders();

            //services.AddIdentityCore<IdentityUser>();
            services.AddControllersWithViews();
            services.AddMvc().AddRazorRuntimeCompilation();
            services.AddRazorPages();
        }

Model: ApplicationUser

namespace MyProject.Models
{
    public class ApplicationUser : IdentityUser
    {
        public string Nickname { get; set; }
    }
}

Applicationdbcontext.cs

namespace MyProject.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
        }
    }
}

Why is the loginpage failing?


Solution

  • It was not only one thing I had to do.

    I found all references of the SignInManager and saw that in many places it still was Connected to IdentityUser. Then I realized I needed to scaffold all identity items again.

    That gave me some new errors, but they were more easy to understand what I should do with, dont remember all of them. But the most important was SignInManager<ApplicationUser> failed three places. Then I had to add the exact location: myProject.Models.ApplicationUser instead of only ApplicationUser