13

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?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
comp32
  • 201
  • 1
  • 5
  • 13
  • 1
    What is the error thrown ? Have you tried to create a scope first `app.Services.CreateScope()` and then call `GetService` on the scope ? – Hazrelle Dec 16 '21 at 22:39
  • https://github.com/davidfowl/CommunityStandUpMinimalAPI/blob/main/TodoApi/Program.cs – ErikEJ Dec 17 '21 at 13:16

1 Answers1

26

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
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132