mskuratowski
mskuratowski

Reputation: 4124

Inject ApplicationDbContext into Configure method in Startup

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.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            }
            else
            {
                options.UseSqlite("Data Source=travelingowe.db");
            }
        });

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

Upvotes: 2

Views: 3937

Answers (2)

Krzysztof Branicki
Krzysztof Branicki

Reputation: 7837

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
}

EDIT

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

Upvotes: 5

davidfowl
davidfowl

Reputation: 38764

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 https://github.com/aspnet/Hosting/pull/1106 for more details.

Upvotes: 11

Related Questions