Inject ApplicationDbContext into Configure method in Startup

放肆的年华 提交于 2020-05-29 11:52:07

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/45231235/inject-applicationdbcontext-into-configure-method-in-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!