comp32
comp32

Reputation: 241

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?

Upvotes: 17

Views: 16942

Answers (1)

Guru Stron
Guru Stron

Reputation: 143098

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
}

Upvotes: 32

Related Questions