title: Cannot resolve scoped service from root provider. ASP.NET MVC app App
body: <p>I am doing Store application with Pro ASP.NET Core MVC 6th Edition by Adam Freeman. The example in book is made in Core 1.0, and I am using Core 3.0. I get error as below, while trying to seed data to my database (entityFramework).</p>
  
  <blockquote>
    <p>System.InvalidOperationException: 'Cannot resolve scoped service
    'BookStore.Models.ApplicationDbContext' from root provider.'</p>
  </blockquote>
  
  <p>Below is my code:</p>
  
  <pre><code> public class SeedData
      {
          public static void EnsurePopulated(IApplicationBuilder app)
          {
              ApplicationDbContext context = app.ApplicationServices.GetRequiredService&lt;ApplicationDbContext&gt;();
              if (!context.Products.Any())
              {
                  context.Products.AddRange(
                      new Product {
                          Name = "Witcher",
                          Description = "Geralt the Witcher",
                          Category = "Fantasy",
                          Price = 30 }
                      );
                  context.SaveChanges();
              }
          }
  </code></pre>
  
  <p>Startup Class:</p>
  
  <pre><code>public class Startup
  {
      public IConfiguration Configuration { get; }
  
      public Startup(IConfiguration configuration, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
      {
          Configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json").Build();
      }
  
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt; options.UseSqlServer(Configuration["Data:BookStoreProducts:ConnectionString"]));
          services.AddTransient&lt;IProductRepository, EFProductRepository&gt;();
          services.AddControllersWithViews();
      }
  
      public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
          else
          {
              app.UseExceptionHandler("/Home/Error");
              app.UseHsts();
          }
          app.UseHttpsRedirection();
          app.UseStaticFiles();
          app.UseRouting();
          app.UseAuthorization();
  
          app.UseEndpoints(endpoints =&gt;
          {
              endpoints.MapControllerRoute(
                  name: "default",
                  pattern: "{controller=Product}/{action=List}/{id?}");
          });
          SeedData.EnsurePopulated(app);
      }
  }
  </code></pre>
  
  <p>And Program.cs</p>
  
  <pre><code>public class Program
  {
      public static void Main(string[] args)
      {
          CreateHostBuilder(args).Build().Run();
      }
  
      public static IHostBuilder CreateHostBuilder(string[] args) =&gt;
          Host.CreateDefaultBuilder(args)
              .ConfigureWebHostDefaults(webBuilder =&gt;
              {
                  webBuilder.UseStartup&lt;Startup&gt;();
              });
  }
  </code></pre>
  
  <p>I am rather new in dependency injection so some explanation what is happening would be nice. I am searchin answer online for more than two hours without any result.</p>
  
  <p>And more about the error:</p>
  
  <blockquote>
    <p>at
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type
    serviceType, IServiceScope scope, IServiceScope rootScope)    at
    Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type
    serviceType, IServiceScope scope)    at
    Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type
    serviceType, ServiceProviderEngineScope serviceProviderEngineScope)<br>
    at
    Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type
    serviceType)    at
    Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider
    provider, Type serviceType)    at
    Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider
    provider)    at
    BookStore.Models.SeedData.EnsurePopulated(IApplicationBuilder app) in
    C:\Users\Piotr\source\repos\Store\BookStore\Models\SeedData.cs:line 12
    at BookStore.Startup.Configure(IApplicationBuilder app,
    IWebHostEnvironment env, ILoggerFactory loggerFactory,
    ApplicationDbContext context) in
    C:\Users\Piotr\source\repos\Store\BookStore\Startup.cs:line 51    at
    System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
    arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags
    invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)<br>
    at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object
    instance, IApplicationBuilder builder)    at
    Microsoft.AspNetCore.Hosting.ConfigureBuilder.&lt;>c__DisplayClass4_0.b__0(IApplicationBuilder
    builder)    at
    Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.&lt;>c__DisplayClass13_0.b__2(IApplicationBuilder
    app)    at
    Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.&lt;>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder
    builder)    at
    Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.&lt;>c__DisplayClass2_0.b__0(IApplicationBuilder
    app)    at
    Microsoft.AspNetCore.HostFilteringStartupFilter.&lt;>c__DisplayClass0_0.b__0(IApplicationBuilder
    app)    at
    Microsoft.AspNetCore.Hosting.GenericWebHostService.d__31.MoveNext()</p>
  </blockquote>
  
  <p>So the solution was:</p>
  
  <pre><code>var scopeeee = app.ApplicationServices.CreateScope();
  
  ApplicationDbContext context = scopeeee.ServiceProvider.GetRequiredService&lt;ApplicationDbContext&gt;();
  </code></pre>
  
  <p>Added at the beggining of EnsurePopulated method. Thanks!</p>