I wrote a class to seed the database with data. When debugging it it stacks on await IdentitySeedData.EnsurePopulated(service); Probably the problem is with usermanager.createasync(). Take a look:
namespace SportStore1
{
public class Program
{
public static void Main(string[] args)
{
var Host = BuildWebHost(args);
var Scopes = Host.Services.GetRequiredService<IServiceScopeFactory>();
using (var scope = Scopes.CreateScope())
{
var service = scope.ServiceProvider;
SeedDataFunc(service);
SeedIdentityDataFunc(service);
}
Host.Run();
}
public static void SeedDataFunc(IServiceProvider service)
{
SeedData.EnsurePopulated(service);
}
public static async void SeedIdentityDataFunc(IServiceProvider service)
{
await IdentitySeedData.EnsurePopulated(service);
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
/*
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
*/
}
}
namespace SportStore1.Data
{
public static class IdentitySeedData
{
public static async Task EnsurePopulated(IServiceProvider service)
{
UserManager<IdentityUser> userManager = service.GetRequiredService<UserManager<IdentityUser>>();
IConfiguration configuration = service.GetRequiredService<IConfiguration>();
ApplicationDbContext dbContext = service.GetRequiredService<ApplicationDbContext>();
if (!dbContext.Roles.Any())
{
foreach (var role in Roles)
{
dbContext.Add(role);
await dbContext.SaveChangesAsync();
}
}
if (!dbContext.Users.Any())
{
var user = new IdentityUser() { UserName = configuration["Email"], Email = configuration["Email"], EmailConfirmed = true };
await userManager.CreateAsync(user, configuration["Password"]);
}
if (!dbContext.UserRoles.Any())
{
var roleID = dbContext.Roles.Where(p => p.Name == "Administrator").FirstOrDefault().Id;
var userID = dbContext.Users.Where(p => p.Email == configuration["Email"]).FirstOrDefault().Id;
var userRole = new IdentityUserRole<string>()
{
RoleId = roleID,
UserId = userID
};
dbContext.UserRoles.Add(userRole);
await dbContext.SaveChangesAsync();
}
}
private static List<IdentityRole> Roles = new List<IdentityRole>()
{
new IdentityRole { Name = "Administrator", NormalizedName = "Administrator", ConcurrencyStamp = Guid.NewGuid().ToString() },
new IdentityRole { Name = "Manager", NormalizedName = "Manager", ConcurrencyStamp = Guid.NewGuid().ToString() },
new IdentityRole { Name = "User", NormalizedName = "User", ConcurrencyStamp = Guid.NewGuid().ToString()}
};
}
}
It stacks on await IdentitySeedData.EnsurePopulated(service) with a message System.ObjectDisposedException: 'Cannot access a disposed object. Object name: 'UserManager`1'.' Any solution?