Data seeding is the process of populating a database with a set of initial data. It is usually performed when the database is first created. These data are usually static and will not change over time. Data seeding is usually used to fill in some basic data, such as users, roles, permissions, products, classifications, etc.
Universal interface design public interface IDataSeedingProvider { Task SeedingAsync(IServiceProvider serviceProvider); } Implement specific interface public class DataSeedingProvider(UserManager<User> userManager) : IDataSeedingProvider { public async Task SeedingAsync(IServiceProvider ServiceProvider) { var user = await userManager.FindByNameAsync("admin"); if (user == null) { await userManager.CreateAsync(new User { UserName = "admin", Email = "admin@test.com" }, "admin"); } } } Register in the container builder.Services.AddTransient<IDataSeedingProvider, DataSeedingProvider>(); Automated execution of extensions public static class DataSeedingExtensions { public static IApplicationBuilder UseDataSeedingProviders(this IApplicationBuilder app) { using var serviceScope = app.ApplicationServices.CreateScope(); var dataSeedingProviders = serviceScope.ServiceProvider.GetServices<IDataSeedingProvider>(); foreach (IDataSeedingProvider dataSeedingProvider in dataSeedingProviders) { dataSeedingProvider.SeedingAsync(serviceScope.ServiceProvider).Wait(); } return app; } } Automatic registration implementation public static class DataSeedingExtensions { public static IServiceCollection AddDataSeedingProviders(this IServiceCollection services, Assembly? assembly = null) { assembly ??= Assembly.GetCallingAssembly(); var dataSeedProviders = assembly.ExportedTypes.Where(t => t.IsAssignableTo(typeof(IDataSeedingProvider)) && t.IsClass); dataSeedProviders.ToList().ForEach(t => services.AddTransient(typeof(IDataSeedingProvider), t)); return services; } } Execution order problem The execution order of automatically registered providers is uncertain. If you need to determine the execution order, you can design the Order attribute, and then order execution according to the Order attribute in the UseDataSeedingProviders method.
...