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.
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 ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With