public class DbInitializer
{
public static async Task CreateAdmin(IServiceProvider service)
{
UserManager<AppUser> userManager = service.GetRequiredService<UserManager<AppUser>>();
RoleManager<IdentityRole> roleManager = service.GetRequiredService<RoleManager<IdentityRole>>();
string username = "Admin";
string email = "AdminG@example.com";
string pass = "Secrete90";
string role = "Admins";
if(await userManager.FindByNameAsync(username)== null)
{
if(await roleManager.FindByNameAsync(role)== null)
{
await roleManager.CreateAsync(new IdentityRole(role));
}
var user = new AppUser { UserName = username, Email = email };
var result = await userManager.CreateAsync(user, pass);
if (result.Succeeded) { await userManager.AddToRoleAsync(user, role); }
}
}
当我在启动时运行此代码时,我收到一条错误,指出无法在启动类中调整代码的范围。
DbInitializer.CreateAdmin(app.ApplicationServices).Wait();
答案 0 :(得分:1)
在.NET Core 2
调用您的种子逻辑需要移动到Main
类的program.cs
方法。
public static void Main(string[] args) {
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope()) {
var services = scope.ServiceProvider;
var userManager = services.GetRequiredService<UserManager<AppUser>>();
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
DbInitializer.CreateAdmin(userManager, roleManager).Wait();
}
host.Run();
}
public class DbInitializer
{
public static async Task CreateAdmin(UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
{
string username = "Admin";
string email = "AdminG@example.com";
string pass = "Secrete90";
string role = "Admins";
if(await userManager.FindByNameAsync(username)== null)
{
if(await roleManager.FindByNameAsync(role)== null)
{
await roleManager.CreateAsync(new IdentityRole(role));
}
var user = new AppUser { UserName = username, Email = email };
var result = await userManager.CreateAsync(user, pass);
if (result.Succeeded) { await userManager.AddToRoleAsync(user, role); }
}
}