Skip to content

Instantly share code, notes, and snippets.

@Ibro
Created May 24, 2021 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ibro/e149f4f192fcd7f563ef0f4c9847e5e3 to your computer and use it in GitHub Desktop.
Save Ibro/e149f4f192fcd7f563ef0f4c9847e5e3 to your computer and use it in GitHub Desktop.
public interface IDbInitializer {
Task Seed();
}
public class DbInitializer: IDbInitializer {
private readonly ILogger < DbInitializer > _logger;
private readonly UserManager < IdentityUser > _userManager;
private readonly ApplicationDbContext _dbContext;
private readonly IWebHostEnvironment _environment;
public DbInitializer(ILogger < DbInitializer > logger, UserManager < IdentityUser > userManager, ApplicationDbContext dbContext, IWebHostEnvironment environment) {
_logger = logger;
_userManager = userManager;
_dbContext = dbContext;
_environment = environment;
}
public async Task Seed() {
if (!_environment.IsDevelopment()) {
return;
}
_logger.LogInformation("Migrating DB");
await _dbContext.Database.MigrateAsync();
_logger.LogInformation("Migrated DB");
_logger.LogInformation("Seeding Users");
await SeedUsers();
_logger.LogInformation("Seeded Users");
}
private async Task < List < IdentityUser >> SeedUsers() {
if (await _dbContext.Users.CountAsync() >= 2) {
return null;
}
var user1 = await CreateUser("user1@codingblast.com", "Test1234!!!");
var user2 = await CreateUser("user2@codingblast.com", "Test1234!!!");
return new List < IdentityUser > {
user1,
user2
};
}
private async Task < IdentityUser > CreateUser(string userName, string password) {
var user = new IdentityUser {
UserName = userName,
Email = userName
};
var result = await _userManager.CreateAsync(user, password);
if (result.Succeeded) {
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
await _userManager.ConfirmEmailAsync(user, code);
return user;
}
else {
throw new ApplicationException("Couldn't create user");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment