# 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.

{% embed url="<https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services>" %}
Read more about Background tasks on MicrosoftLearn.
{% endembed %}

## Create the Service

{% code overflow="wrap" %}

```csharp
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);
    }
}
```

{% endcode %}

## Register the Service

```csharp
builder.Services.AddHostedService<SetupData>();
```

## Related Articles

{% content-ref url="/pages/1yn0Iz3oAJLrBaNc79Dy" %}
[Product Definitions & Fields](/readme/how-to/entities-from-code/product-definitions-and-fields.md)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dev.ucommerce.net/readme/how-to/entities-from-code/bootstrapping-data-on-startup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
