in src/Services/User/User.Infrastructure/Persistence/ApplicationDbContextSeed.cs [30:66]
public static void InitializeDatabase(IConfiguration configuration)
{
var services = new ServiceCollection();
services.AddLogging();
services.AddInfrastructure(configuration);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
using IServiceScope scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
context.Database.Migrate();
var roleMgr = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
foreach (var role in Enum.GetNames(typeof(Roles)))
{
IdentityRole userRole = roleMgr.FindByNameAsync(role).Result;
if (userRole == null)
{
userRole = new IdentityRole(role);
IdentityResult result = roleMgr.CreateAsync(userRole).Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
Console.WriteLine($"{role} role created");
}
else
{
Console.WriteLine($"{role} role already exists");
}
}
}