'How do I get Identity UserManager in .NET 6.0

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.



Solution 1:[1]

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 ...
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kempeth