Inject ApplicationDbContext into Configure method in Startup

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


I'm using EntityFrameworkCore 2.0.0-preview2-final and I would like to inject the ApplicationDbContext into Configure method in Startup class.

Here's my code:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
    // rest of my code

but when I run my app I'm getting an error message:

System.InvalidOperationException: Cannot resolve scoped service 'ProjectName.Models.ApplicationDbContext' from root provider.

Here's also my code from ConfigureServices method:

services.AddDbContext<ApplicationDbContext>(options =>
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                options.UseSqlite("Data Source=travelingowe.db");

Do you have any idea how can I solve this problem?

7/21/2017 7:16:28 AM

Accepted Answer

This will work in 2.0.0 RTM. We've made it so that there is a scope during the call to Configure so the code you originally wrote will work. See for more details.

7/24/2017 8:08:56 AM

Popular Answer

EF Core DbContext is registered with scoped lifestyle. In ASP native DI container scope is connected to instance of IServiceProvider. Normally when you use your DbContext from Controller there is no problem because ASP creates new scope (new instance of IServiceProvider) for each request and then uses it to resolve everything within this request. However during application startup you don't have request scope so you should create scope yourself. You can do it like this:

var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
    var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
    // rest of your code


As davidfowl stated this will work in 2.0.0 RTM since scoped service provider will be created for Configure method.

Related Questions


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