使用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.CreateAsync
或userManager.AddToRoleAsync
。
答案 0 :(得分:5)
我认为问题在于DbInitializer.Initialize()
方法调用(应标记为async
并返回Task
)未正确等待,因为Startup.Configure
方法必须归还无效。如果您将呼叫更改为等待任务完成的DbInitializer.Initialize().Wait()
,它应该有效。