title: ASP.NET Core 2 Seed Database
body: <p>I've seen some of the similar examples on SO regarding this but I don't know enough about the language just yet to see what I'm doing wrong. I've cobbled together a demo to learn more but I'm having trouble seeding my database.</p>
  <p>I receive the following error:</p>
  <blockquote>
  <p>InvalidOperationException: Cannot resolve scoped service 'demoApp.Models.AppDbContext' from root provider.</p>
  <p>Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider)</p>
  </blockquote>
  <p>Here are the three files in question:</p>
  <p><strong>Models/AppDbContext.cs</strong></p>
  <pre><code>public class AppDbContext : DbContext
  {
      public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options)
      {
  
      }
      public DbSet&lt;Product&gt; Products{ get; set; }
      public DbSet&lt;Category&gt; Categories { get; set; }
  }
  </code></pre>
  <p><strong>Models/DBInitializer.cs</strong></p>
  <pre><code>public static class DbInitializer
  {
      public static void Seed(IApplicationBuilder applicationBuilder)
      {
          //I'm bombing here
          AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService&lt;AppDbContext&gt;();
  
          if (!context.Products.Any())
          {
              // Add range of products
          }
  
          context.SaveChanges();
      }
  
      private static Dictionary&lt;string, Category&gt; _categories;
      public static Dictionary&lt;string, Category&gt; Categories
      {
          get
          {
              if (_categories == null)
              {
                 // Add categories...
              }
  
              return _categories;
          }
      }
  }
  </code></pre>
  <p><strong>Startup.cs</strong></p>
  <pre><code>public Startup(IConfiguration configuration)
  {
      Configuration = configuration;
  }
  
  public IConfiguration Configuration { get; }
  
  public void ConfigureServices(IServiceCollection services)
  {
      services.AddTransient&lt;ICategoryRepository, CategoryRepository&gt;();
      services.AddTransient&lt;IProductRepository, ProductRepository&gt;();
  
      services.AddDbContext&lt;AppDbContext&gt;(options =&gt; 
          options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));
  
      services.AddMvc();
  }
  
  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
          app.UseBrowserLink();
          app.UseStatusCodePages();
          
          // Kersplat!
          DbInitializer.Seed(app);
      }
      else ...
      
      app.UseStaticFiles();
      app.UseMvc(routes =&gt; {...});
  }
  </code></pre>
  <p>Can someone help explain what I'm doing wrong and how to remedy the situation?</p>