Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to call EF Core methods on application startup in my Program.cs file, using the .NET 6 minimal API template and get the following error:

System.InvalidOperationException: 'Cannot resolve scoped service 'Server.Infrastructure.DbContexts.AppDbContext' from root provider.'

// ************** Build Web Application **************

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(configuration.GetConnectionString("AppDb:Postgres")));

// ...

// **************** Web Application *****************

var app = builder.Build();

var dbContext = app.Services.GetService<AppDbContext>(); // error thrown here

if (dbContext != null)
{
    dbContext.Database.EnsureDeleted();
    dbContext.Database.Migrate();
}

// ...

With earlier versions of .NET Core I am aware I can get the DbContext in the Configure method, but how would I get the service with this approach?

like image 528
comp32 Avatar asked Dec 12 '25 15:12

comp32


1 Answers

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
}
like image 153
Guru Stron Avatar answered Dec 15 '25 05:12

Guru Stron