新的.NET 6 Blazor模板去掉了Startup.cs
,并将所有内容压缩为更平坦的结构。
我以前使用过Startup.cs
的Configure
方法来注入UserManager
并为管理员用户种子。
在新结构中,我怎样才能做到这一点?
我还没有找到从任何地方获得UserManager
的方法。
Program.cs
中的以下更改允许像以前一样调用DBInitializer:
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);
}
用于引用的初始化程序:
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 ...
}
}
以下是我如何在.NET 6.0&7.0
在您的program.cs
中
var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
// .. You can do migration here.
await DbSeeder.SeedUsers(userManager, roleManager);
DbSeeder:
public static class DbSeeder
{
public static async void SeedUsers(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> rolemanger){
string[] roles = { "Admin", "User", "Guest", "SuperAdmin" };
foreach (var role in roles)
{
var roleExist = await roleManager.RoleExistsAsync(role);
if (!roleExist)
{
await roleManager.CreateAsync(new IdentityRole() { Name = role });
}
}
// This will hold the User, Password & Role
List<(ApplicationUser, string, string)> usersToCreate = new();
var appUser = new ApplicationUser
{
UserName = "user@localhost",
Email = "user@localhost",
EmailConfirmed = true
};
usersToCreate.Add((appUser, "User$14123!", "User"));
// You can add more users ...
foreach (var item in usersToCreate)
{
var newUser = item.Item1;
var userName = newUser.UserName;
var password = item.Item2;
var role = item.Item3;
var user = await userManager.FindByNameAsync(userName);
if (user == null)
{
var result = await userManager.CreateAsync(newUser, password);
if (result.Succeeded)
{
await userManager.AddToRoleAsync(newUser, role);
}
}
}
}
}
使用asp.net核心3.1创建项目,然后将其转换为6.0