How do I get Identity UserManager in .NET 6.0

Viewed 1558

The new .NET 6 Blazor templates have done away with Startup.cs and condensed everything into a much flatter structure.

I've previously used the Startup.cs's Configure method to inject the UserManager and seed an admin user.

How can I do the same in the new structure?

I've not found a way to get the UserManager from anywhere.

2 Answers

The following changes in Program.cs allow the DBInitializer to be called as before:

var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
    var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
    ApplicationDbInitializer.Seed(userManager, roleManager);
}

Initializer for reference:

public static class ApplicationDbInitializer
{
    public static void Seed(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        bool adminRoleReady = false;
        bool adminUserReady = false;

        if (roleManager.FindByNameAsync("Admin").Result == null)
        {
            var role = new IdentityRole()
            {
                Name = "Admin",
            };

            var res = roleManager.CreateAsync(role).Result;

            adminRoleReady = res.Succeeded;
        }

        // ... more ...
    }
}

create your project with asp.net core 3.1 then convert it to 6.0

Related