UserManager - 访问处置对象

时间:2017-10-10 15:38:31

标签: asp.net entity-framework asp.net-core asp.net-identity

使用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

1 个答案:

答案 0 :(得分:5)

我认为问题在于DbInitializer.Initialize()方法调用(应标记为async并返回Task)未正确等待,因为Startup.Configure方法必须归还无效。如果您将呼叫更改为等待任务完成的DbInitializer.Initialize().Wait(),它应该有效。