This article is a general recommendation for setting up data on startup. This can be useful when bootstrapping a project and setting up Data Types, Definitions, and other entities.
When to create the data?
We recommend placing the logic for creating data into a HostedService. By inheriting BackgroundService, you create a potentially long-running job activated once at app startup.
Create the Service
publicclassSetupData:BackgroundService{privatereadonlyIServiceProvider _serviceProvider;publicSetupData(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; }protectedoverrideasyncTaskExecuteAsync(CancellationToken stoppingToken) {awaitusingvar asyncScope =_serviceProvider.CreateAsyncScope();var dbContext =asyncScope.ServiceProvider.GetRequiredService<UcommerceDbContext>(); // Set up data using dbContextawaitdbContext.SaveChangesAsync(stoppingToken); }}