Hi @Khanh Duy Van Ba ,
From your code and description, I assume you want to call the method in the interface class to seed data for the Identity table, right? If that is the case, you can refer the following sample:
Interface and the Initialize method:
public interface IDataRepository
{
public void Initialize(ApplicationDbContext db, UserManager<IdentityUser> userManager);
}
public class DataRepository : IDataRepository
{
public void Initialize(ApplicationDbContext db, UserManager<IdentityUser> _userManager)
{
var user = _userManager.Users.ToList();
//you can seed the Identity User table from here.
}
}
Register the service in the ConfigureServices method: (I didn't configure the Role Manager, you can set it in your application)
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddScoped<IDataRepository, DataRepository>();
Then, in the program.cs
file, use the GetRequiredService()
method to get the relate service:
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
//required using Microsoft.Extensions.DependencyInjection;
// required using Microsoft.AspNetCore.Identity;
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var dbcontext = services.GetRequiredService<ApplicationDbContext>();
var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
var repository = services.GetRequiredService<IDataRepository>();
repository.Initialize(dbcontext, userManager);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
}
The result as below:
Besides, you can also refer the following article to initialize data into database:
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion