'未注册类型为'Identity.UserManager`1 [ProjectName.ApplicationUser]'的服务。在销毁容器时可注册)'

时间:2020-09-10 00:39:34

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

我正在尝试向我的项目添加一些角色和用户。我正在使用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();

    }

当我运行项目时,它给我错误“ System.AggregateException:'类型为'Microsoft.AspNetCore.Identity.UserManager`1 [ProjectName.ApplicationUser]'的服务已被注册。当容器被销毁时可注册)'。 “在CreateRoles(serviceProvider).Wait();中; 为什么会这样?

1 个答案:

答案 0 :(得分:1)

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

有关更多信息,请查看官方docs

相关问题