将ApplicationDbContext注入Startup中的Configure方法

Cie*_*eja 2 c# entity-framework entity-framework-core .net-core asp.net-core

我正在使用EntityFrameworkCore 2.0.0-preview2-final,我想将ApplicationDbContext注入Startup类的Configure方法.

这是我的代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
{ 
    // rest of my code
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行我的应用程序时,我收到一条错误消息:

System.InvalidOperationException:无法从根提供程序解析作用域服务"ProjectName.Models.ApplicationDbContext".

这也是我在ConfigureServices方法中的代码:

services.AddDbContext<ApplicationDbContext>(options =>
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            }
            else
            {
                options.UseSqlite("Data Source=travelingowe.db");
            }
        });
Run Code Online (Sandbox Code Playgroud)

你知道我怎么能解决这个问题?

dav*_*owl 9

这将在2.0.0 RTM中运行.我们已经做到这一点,因此在调用Configure期间有一个范围,因此您最初编写的代码将起作用.有关详细信息,请参阅https://github.com/aspnet/Hosting/pull/1106.


Krz*_*cki 5

EF CoreDbContext注册了范围生活方式。在 ASP 本机 DI 容器范围连接到IServiceProvider. 通常,当您使用DbContextfrom Controller 时没有问题,因为 ASPIServiceProvider为每个请求创建新的范围( 的新实例),然后使用它来解决此请求中的所有内容。但是在应用程序启动期间,您没有请求范围,因此您应该自己创建范围。你可以这样做:

var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
    var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
    // rest of your code
}
Run Code Online (Sandbox Code Playgroud)

编辑

正如 davidfowl 所说,这将在 2.0.0 RTM 中工作,因为将为Configure方法创建范围服务提供者。