我似乎没有得到它。我只是想从VS2015 Web核心模板创建一些用户(理想情况下来自核心控制台应用程序,但似乎需要更多设置)
所以我从Startup.cs中调用Initialize
UserManager为NULL,因此无效。我错过了什么?
DbInitializer.Initialize(上下文);
public static class DbInitializer
{
public static UserManager<ApplicationUser> UserManager { get; private set; }
public static async void Initialize(ApplicationDbContext context)
{
var user = new ApplicationUser { UserName = "abc@xxx.com" };
IdentityResult result = await UserManager.CreateAsync(user, "password");
//var ttime = DateTime.Now;
//for (int j = 0; j < 100; j++)
//{
// var start = DateTime.Now;
// for (int i = 0; i < 100; i++)
// {
// var email = "user" + ((j * 100) + i) + "@constoso.com";
// var user = new ApplicationUser { UserName = "Bob", Email = email };
// var result = await UserManager.CreateAsync(user, "ccc");
// }
//}
}
}
答案 0 :(得分:1)
如果你坚持从Startup中调用它,请传递ServiceProvider并从那个获取Usermanager:
DbInitializer.Initialize(app.ApplicationServices);
public static async void Initialize(IServiceProvider services)
{
using (var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope()) {
var manager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var user = new ApplicationUser { UserName = "abc@xxx.com" };
var result = await manager.CreateAsync(user, "password");
}
}