简体   繁体   中英

'No service for type 'Identity.UserManager`1[ProjectName.ApplicationUser]' has been registered.able when container is destroy)'

I'm trying to add some roles and users to my project. I'm using ASP.NET Core version 3.1. Right now I tried this in my Startup class:

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

            }
        }
    }

and

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

    }

When I run the project it gives me the error "System.AggregateException: 'No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[ProjectName.ApplicationUser]' has been registered.able when container is destroy)'" in CreateRoles(serviceProvider).Wait(); Why is this happening?

Try to add services.AddDefaultIdentity<ApplicationUser>(); in your Startup.cs .

For more info you can check the official docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM