Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 263
Kempeth Avatar asked Sep 02 '25 16:09

Kempeth


1 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 ...
    }
}
like image 197
Kempeth Avatar answered Sep 06 '25 15:09

Kempeth