Cannot resolve DbContext in ASP.NET Core 2.0

You're registering SGDTPContext as a scoped service and then attempting to access it outside of a scope. To create a scope inside your SeedDatabase method, use the following:

using (var serviceScope = app.ApplicationServices.CreateScope())
{
    var context = serviceScope.ServiceProvider.GetService<SGDTPContext>();

    // Seed the database.
}

Credit to @khellang for pointing out the CreateScope extension method in the comments and to @Tseng's comment and answer re how to implement seeding in EF Core 2.


Was getting this error while following the official ASP.Net MVC Core tutorial, in the section where you are supposed to add seeded data to your application. Long story short, adding these two lines

 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.DependencyInjection;

to the SeedData class solved it for me:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace MvcMovie.Models
{
public static class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new MvcMovieContext(

           serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
        {
            // Look for any movies.
            if (context.Movie.Any())
            {
                return;   // DB has been seeded
            }
  ...

Can't tell you the WHY, but these were two of the options I got from following the Alt + Enter quick fix option.