如何在启动时/使用 Web 模板手动创建 ASP.NET 标识用户



我似乎不明白。我只想从VS2015 Web核心模板创建一些用户(最好是从核心控制台应用程序创建,但这似乎需要更多的设置)

所以我从启动调用初始化.cs

用户管理器为空,因此它不起作用。我错过了什么?

DbInitializer.Initialize(context);

  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");
        //    }
        //}
    }
}

如果您坚持从 Startup 调用它,请传递 ServiceProvider 并从该 ServiceManager 获取 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");
    }
}

相关内容

  • 没有找到相关文章

最新更新