【问题标题】:Some Services Are Not Able To Be Constructed identity role某些服务无法构造身份角色
【发布时间】:2021-11-19 15:40:35
【问题描述】:

我的项目中有Startup.csIdentityHostingStartup.cs。将行 .AddRoles<IdentityRole>() 添加到 IdentityHostingStartup.cs 后出现错误:

部分服务无法构建

InvalidOperationException:尝试激活 Microsoft.AspNetCore.Identity.RoleManager1[Microsoft.AspNetCore.Identity.IdentityRole] 时,无法解析类型 Microsoft.AspNetCore.Identity.IRoleStore1[Microsoft.AspNetCore.Identity.IdentityRole] 的服务。

添加services.AddScoped/Transient(IRoleStore,RoleManager) 不起作用导致我收到错误:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0311?f1url=%3FappId%3Droslyn%26k%3Dk(CS0311)

Startup.cs


 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                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.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

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

                endpoints.MapRazorPages();
            });


            CreateRoles(serviceProvider);
        }

private void CreateRoles(IServiceProvider serviceProvider)
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            string email = "someEmail";

            Task<IdentityResult> roleResult;
            var adminRoleExists = roleManager.RoleExistsAsync("Admin").Result;       
            if(!adminRoleExists)
            {
                roleResult = roleManager.CreateAsync(new IdentityRole("Admin"));
                roleResult.Wait();
            }

            var userRoleExists = roleManager.RoleExistsAsync("User").Result;
            if (!userRoleExists)
            {
                roleResult = roleManager.CreateAsync(new IdentityRole("User"));
                roleResult.Wait();
            }

            Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
            testUser.Wait();


            if (testUser.Result == null)
            {
                ApplicationUser administrator = new ApplicationUser();
                administrator.Email = email;
                administrator.UserName = email;

                Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "2137jp2gmd");
                newUser.Wait();

                if (newUser.Result.Succeeded)
                {
                    Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Admin");
                    newUserRole.Wait();
                }
            }

        }

IdentityHostingStartup.cs

 public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureServices((context, services) => {
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(
                        context.Configuration.GetConnectionString("AuthDbContextConnection")));

                services.AddDefaultIdentity<ApplicationUser>(options =>
                {
                    options.Password.RequireUppercase = false;
                    options.Password.RequireLowercase = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireDigit = false;
                    options.SignIn.RequireConfirmedAccount = false;
                })
                    .AddEntityFrameworkStores<ApplicationDbContext>()
                    .AddRoles<IdentityRole>();

                
            });
        }

【问题讨论】:

  • 您可能需要拨打.AddRoleStore&lt;...&gt;(...) 或类似电话
  • 已添加 .AddRoleStore&lt;IdentityRole&gt;() 现在出现此错误:InvalidOperationException:验证服务描述符时出错 ServiceType:Microsoft.AspNetCore.Identity.ISecurityStampValidator Lifetime:Scoped ImplementationType:Microsoft.AspNetCore.Identity.SecurityStampValidator1[BugTracker.Areas。 Identity.Data.ApplicationUser]:实现类型“Microsoft.AspNetCore.Identity.IdentityRole”无法转换为服务类型 Microsoft.AspNetCore.Identity.IRoleStore1[Microsoft.AspNetCore.Identity.IdentityRole]'

标签: c# asp.net-core asp.net-core-identity


【解决方案1】:

IdentityHostupStartup.cs

改变

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

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

我不知道为什么,但是以某种方式将这两条线相互切换是可行的,一切都很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 2021-12-12
    • 2021-07-07
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多