我想在启动时创建5个用户并仅使用这些帐户。标准注册机制被禁用。
所以我找到了这个代码示例,但它只适用于在此循环中创建第一个用户。当它尝试创建4个其他用户时,ObjectDisposed Exception正在抛出。
我在github上发现了几乎相同的问题,似乎仍然存在。但是我希望可以有一些解决方法。
//DbInitialize.cs
public async Task Initialize()
{
_context.Database.EnsureCreated();
if (!_context.Roles.Any(r => r.Name == "Administrator"))
{
await _roleManager.CreateAsync(new IdentityRole("Administrator"));
}
if (!_context.Users.Any())
{
for (int i = 0; i < 5; i++)
{
string userName = "testuser" + (i + 1);
string password = "Abc123456789";
//line where exception occures when i=1
var result =
await _userManager.CreateAsync(
new ApplicationUser {UserName = userName, Email = userName, EmailConfirmed = true},
password);
if (result.Succeeded)
{
var user = await _userManager.FindByEmailAsync(userName);
await _userManager.AddToRoleAsync(user, "Administrator");
}
}
}
}
//startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().AddViewOptions(options => options.HtmlHelperOptions.ClientValidationEnabled = false);
// Add Database Initializer
services.AddScoped<IDbInitializer, DbInitializer>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IDbInitializer dbInitializer)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseBrowserLink();
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
dbInitializer.Initialize();
}
注意:_userManager的初始化在DbInitializer类
中 private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public DbInitializer(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}