使用ASP.NET Core 2。

我正在尝试初始化一些应用程序范围的数据。为此,我创建了一个名为DbInitializer的新类,一个名为IDbInitializer的接口,并在AddScoped中向Startup.ConfigureServices注册了它们。

然后从Startup.Configure调用DbInitializer.Initialize(),在该方法内部,有几个对UserManager的调用:

if (appDbContext.Roles.All(i => i.Name != adminGroupName))
{
    await roleManager.CreateAsync(new IdentityRole(adminGroupName));
};
var role = appDbContext.Roles.First(i => i.Name == adminGroupName);

if (appDbContext.Users.All(i => i.UserName != adminSettings.Username))
{
    await userManager.CreateAsync(new ApplicationUser { UserName = adminSettings.Username,
                                                        Email = adminSettings.Username,
                                                        FirstName = adminSettings.FirstName,
                                                        LastName = adminSettings.LastName,
                                                        EmailConfirmed = true }, adminSettings.Password);
}
var adminUser = appDbContext.Users.First(i => i.UserName == adminSettings.Username);

if (!appDbContext.UserRoles.Any(i => i.RoleId == role.Id && i.UserId == adminUser.Id))
{
    await userManager.AddToRoleAsync(adminUser, role.Name);
}


问题是我随机得到异常


无法访问已处置的对象


来自userManager.CreateAsyncuserManager.AddToRoleAsync

最佳答案

我相信问题是您的DbInitializer.Initialize()方法调用(应标记为async并返回Task)未正确等待,因为Startup.Configure方法必须返回void。如果将呼叫更改为DbInitializer.Initialize().Wait(),它将等待任务完成,则该方法应该起作用。

10-08 08:07