How to access DbContext in .NET 6 minimal API Program.cs

Scoped services require scope to be resolved. You can create scope via ServiceProviderServiceExtensions.CreateScope:

using(var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    // use context
}

Leave a Comment