Bootstrapping data on startup

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

public class SetupData : BackgroundService
{
    private readonly IServiceProvider _serviceProvider;

    public SetupData(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await using var asyncScope = _serviceProvider.CreateAsyncScope();
        var dbContext = asyncScope.ServiceProvider.GetRequiredService<UcommerceDbContext>();

        // Set up data using dbContext

        await dbContext.SaveChangesAsync(stoppingToken);
    }
}

Register the Service

builder.Services.AddHostedService<SetupData>();

pageProduct Definitions & Fields

Last updated