2017-10-10 72 views
0

使用ASP.NET Core 2.UserManager - 訪問處置對象

我試圖啓動一些應用程序範圍的數據。爲此,我創建了一個名爲DbInitializer的新類,名爲IDbInitializer的界面,並在Startup.ConfigureServices中將其註冊爲AddScoped

然後從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); 
} 

的問題是,我得到,隨機異常

無法訪問處置對象

from userManager.CreateAsync or userManager.AddToRoleAsync

+0

是DbInitializer.Initialize()異步?發佈它的原型 – ingvar

+0

是的,它在DbInitializer中聲明爲:public async void Initialize() – user1044169

+0

重命名爲公共異步Task Initialize()help? – ingvar

回答

2

我認爲問題在於您的DbInitializer.Initialize()方法調用(應標記爲async並返回Task)未被正確等待,因爲Startup.Configure方法必須返回void。如果您將呼叫更改爲DbInitializer.Initialize().Wait(),它將等待任務完成。

相關問題