Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🗣️ Consider an IHostedService instead of inside the Program.cs for Migrate & Seed the DB #226

Open
Hona opened this issue Dec 19, 2023 · 0 comments

Comments

@Hona
Copy link
Member

Hona commented Dec 19, 2023

We currently have:

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    ...

    // Initialise and seed database
    using var scope = app.Services.CreateScope();
    var initializer = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitializer>();
    await initializer.InitializeAsync();
    await initializer.SeedAsync();
}

Consider the following from MS guys
https://github.com/davidfowl/BlazorBlog/blob/main/MyBlog.Api/Data/MigrationHostedService.cs#L6

public async Task StartAsync(CancellationToken cancellationToken)
    {
        await using var scope = serviceScopeFactory.CreateAsyncScope();
        var context = scope.ServiceProvider.GetRequiredService<TContext>();

        var strategy = context.Database.CreateExecutionStrategy();

        await strategy.ExecuteAsync(async () =>
        {
            await context.Database.EnsureCreatedAsync(cancellationToken: cancellationToken);
            await context.Database.MigrateAsync(cancellationToken: cancellationToken);
        });
    }

Note that this won't cause issues because StartAsync quote:

StartAsync is called before:
The app's request processing pipeline is configured.
The server is started and IApplicationLifetime.ApplicationStarted is triggered.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-8.0&tabs=visual-studio#startasync

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

No branches or pull requests

1 participant