Can't create an instance of the DbContext in AspNetCore 2.0 application using DI for options

asp.net-core c# entity-framework-core

Question

According to the docs I'm supposed to use the following statement to access my data in the DB (which always works great when using the non-DI based context approach).

using (Context context = new Context())
  return context.Workers.ToList()

However, now I'm trying to follow the docs for how to deploy EF context based on DI provided by the service configuration like this.

public void ConfigureServices(IServiceCollection services)
{
  ...
  string connection = "...";
  services.AddDbContext<Context>(_ => _.UseSqlServer(connection));
}

This seems to be working when manipulating the database schema but produces an error when trying to query for data (the first statement above) due to the fact that there's no default constructor in the context class, which looks like this.

public class Context : DbContext
{
  public Context(DbContextOptions<Context> options) : base(options) { }

  public DbSet<Worker> Workers { get; set; }

  protected override void OnModelCreating(ModelBuilder builder) { ... }
}

Am I supposed to introduce a parameterless constructor in additional to the one i already have? Or should I provide the options object by myself? (Frankly speaking, I was expecting the DI to provide it for me automagically, so I feel a bit confused if I've understood the concept correctly.)

I couldn't find any info on this particular issue in the docs.

1
2
1/6/2018 7:14:04 PM

Accepted Answer

Now that I understood what you meant, this is completely wrong:

using (Context context = new Context())
  return context.Workers.ToList();

You are not supposed to ever create instances yourself when using Dependency Injection. This is how your code should look like:

public class HomeController : Controller
{
    private readonly Context context;

    public HomeController(Context ctx)
    {
        context = ctx;
    }

    public List<Worker> GetWorkers()
    {
        return context.Workers.ToList();
    }
}

I'd suggest you to follow this Microsoft Docs article on DI which explains both DI and how to work with it (as well as configuring Entity Framework Core) on ASP.NET Core.

1
1/6/2018 7:34:07 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow