首页 > 解决方案 > 'Identity.UserManager`1[ProjectName.ApplicationUser]' 类型的服务没有注册。当容器被销毁时可用)'

问题描述

我正在尝试将一些角色和用户添加到我的项目中。我正在使用 ASP.NET Core 3.1 版。现在我在我的 Startup 课程中尝试了这个:

             private async Task CreateRoles(IServiceProvider serviceProvider)
    {
        //initializing custom roles 
        var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
        string[] roleNames = { "Admin", "Operacional"};
        IdentityResult roleResult;

        foreach (var roleName in roleNames)
        {
            var roleExist = await RoleManager.RoleExistsAsync(roleName);
            // ensure that the role does not exist
            if (!roleExist)
            {
                //create the roles and seed them to the database: 
                roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
            }
        }

        // find the user with the admin email 
        var _user = await UserManager.FindByEmailAsync("admin@gmail.com");

        // check if the user exists
        if (_user == null)
        {
            //Here you could create the super admin who will maintain the web app
            var poweruser = new ApplicationUser
            {
                UserName = "Admin",
                Email = "admin@gmail.com",
            };
            string adminPassword = "Abc*123";

            var createPowerUser = await UserManager.CreateAsync(poweruser, adminPassword);
            if (createPowerUser.Succeeded)
            {
                //here we tie the new user to the role
                await UserManager.AddToRoleAsync(poweruser, "Admin");

            }
        }
    }

           public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        //SIGNAL R

        //String caminho = configuration["AppSettings:Servidor"] + "/myHub";
        String caminho = Configuration["AppSettings:Servidor"] + "/myHub";

        //endpoints.MapHub<MyHub>(caminho);
        //app.UseSignalR(route =>
        //{
        //    route.MapHub<MyHub>(caminho);

        //});

        app.UseRouting();
       app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<MyHub>("/myHub");
            endpoints.MapControllerRoute(
                name: "default",
               pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });

        CreateRoles(serviceProvider).Wait();

    }

当我运行该项目时,它在 CreateRoles 中给我错误“System.AggregateException:'No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[ProjectName.ApplicationUser]' has been registered.able when container is destroy)'” (服务提供者).Wait(); 为什么会这样?

标签: c#asp.net-coreauthenticationidentityroles

解决方案


尝试添加services.AddDefaultIdentity<ApplicationUser>();您的Startup.cs.

有关更多信息,您可以查看官方文档


推荐阅读