asp.net-core-mvcservice-provider

No service for type Identity.RoleManager - Identity.IdentityRole has been registered error


I use Microsoft Identity for the first time. I configured users and roles with IdentityUser and IdentityRole. I want to assign a role to users in Startup.cs. I wrote a method to make it which is

private async Task CreateUserRoles(IServiceProvider serviceProvider) {


      var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<int>>>();
      var userManager = serviceProvider.GetRequiredService<UserManager<User>>();

      var roleName = "Super Admin";
      var roleCheck = await roleManager.RoleExistsAsync(roleName);
      if (!roleCheck) {
            Role role = new Role();
            role.Name = roleName;
            IdentityResult result = roleManager.CreateAsync(role).Result;
            //IdentityResult roleResult = await roleManager.CreateAsync(new IdentityRole<int>(roleName));
      }
      User user = new User();
      user.UserName = "someone";
      user.Password = "someone";
      user.Email = "someone@gmail.com";
      ApplicationDbContext context = new ApplicationDbContext();
      context.Users.Add(user);
      context.SaveChanges();
      user = await userManager.FindByEmailAsync("someone@gmail.com");

      await userManager.AddToRoleAsync(user, roleName);
}

Hovewer there is a problem :

No service for type 
'Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole1[System.Int32]]' has been registered.

How can I fix it?

Here is a Startup.cs

  public class Startup {
        public Startup(IConfiguration configuration) {
              Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
              services.Configure<CookiePolicyOptions>(options => {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
              });

              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
              services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


              // Add MVC services to the services container.
              services.AddMvc();
              services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
              services.AddSession(opt => { opt.Cookie.IsEssential = true; });

              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                          .AddRazorPagesOptions(options => {
                                options.AllowAreas = true;
                                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Settings");
                                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
                          });
              services.AddDbContext<ApplicationDbContext>(options =>
                                options.UseNpgsql("User ID = postgres; Password = sa; Host = localhost; Port = 5432; Database = CCN; Pooling = true;"));

              services.ConfigureApplicationCookie(options => {
                    options.LoginPath = $"/Account/Login"; //options.LoginPath = $"/Identity/Account/Login";
                    options.LogoutPath = $"/Account/Logout";
                    options.AccessDeniedPath = $"/Account/AccessDenied";
              });



              //Password settings
              services.AddIdentity<User, Role>(o => {
                    o.Password.RequireDigit = false;
                    o.Password.RequireLowercase = false;
                    o.Password.RequireUppercase = false;
                    o.Password.RequireNonAlphanumeric = false;
                    //o.Password.RequiredLength = 3;

              }).AddEntityFrameworkStores<ApplicationDbContext>().AddRoles<IdentityRole>()
              .AddDefaultTokenProviders();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services) {

              app.UseDeveloperExceptionPage();
              app.UseStatusCodePages();
              if (env.IsDevelopment()) {
                    app.UseDeveloperExceptionPage();
              }
              else {
                    app.UseExceptionHandler("/Home/Index");
                    app.UseHsts();
              }

              app.UseHttpsRedirection();
              app.UseStaticFiles();
              app.UseCookiePolicy();
              //Enable session 
              app.UseSession();


              app.UseAuthentication();

              app.UseMvc(routes => {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}");
              });

              //Create user role and assign it  
              CreateUserRoles(services).Wait();

        }

  }

Solution

  • I tried those solutions but it didn't work. Then I recognize that I created an entity called Role which is derived from IdentityRole and its id data type is int. I changed

    var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<int>>>();
    

    this line with

    var roleManager = serviceProvider.GetRequiredService<RoleManager<Role>>();
    

    this one. Then it works. On the other hand, thanks for your help!