没有为Identity.RoleManager类型提供的服务-Identity.IdentityRole已被注册错误

时间:2019-06-24 12:32:51

标签: asp.net-core-mvc service-provider

我第一次使用Microsoft身份。我使用IdentityUser和IdentityRole配置了用户和角色。我想在Startup.cs中为用户分配一个角色。我写了一种制作方法

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);
}

但是有问题:

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

我该如何解决?

这是一个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();

        }

  }

2 个答案:

答案 0 :(得分:0)

  

没有类型的服务   已注册“ Microsoft.AspNetCore.Identity.RoleManager1 [Microsoft.AspNetCore.Identity.IdentityRole1 [System.Int32]]”。

在注册DB::select以获得AspNetCore身份时,RoleManager <>类型将作为IdentityRole注册到ServiceCollection。

每当您要解析RoleManager<IdentityRole>时,都将在启动时注册的身份角色模型指定为type参数。在您的特定情况下为RoleManager<>。 / p>

在生成的服务提供商上调用RoleManager<IdentityRole>时,GetRequiredService<RoleManager<IdentityRole>>()将引发以上异常。

进行以下修改:

在CreateUserRoles中

GetRequiredService<RoleManager<IdentityRole>>()

在DI容器中注册角色服务(选择两种方法之一)

1。使用AddIdentity()

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

2。使用AddDefaultIdentity,使用services.AddIdentity<User, IdentityRole() .AddDefaultUI() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); 方法包含角色

[AddRoles][1]

参考:AddDefaultIdentity and AddIdentity

答案 1 :(得分:0)

我尝试了这些解决方案,但是没有用。然后,我认识到我创建了一个名为Role的实体,该实体是从IdentityRole派生的,其id数据类型为int。我改变了

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

此行与

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

这一个。然后就可以了。 另一方面,谢谢您的帮助!