0

when I try to run the line:

ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>()

I get presented with an error: "System.InvalidOperationException: 'Cannot resolve scoped service 'SportsStore.Models.ApplicationDbContext' from root provider.'"

I saw an answer to a similar question(Cannot resolve scoped service from root provider - solution to error?), but idk how to do it in asp.net core mvc 6.0.

  • 1
    Disabling scope-validation means _sweeping a problem under the rug_ and it will only make things worse because then it will surprise you _after_ app startup. Instead, fix your `ConfigureServices` method. – Dai Mar 23 '22 at 07:05

1 Answers1

2

Have you tried:

using (var scope = app.ApplicationServices.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
    // Do something...
}
Oliver
  • 43,366
  • 8
  • 94
  • 151