将 ApplicationDbContext 注入 Startup 中的 Configure 方法 [英] Inject ApplicationDbContext into Configure method in Startup

查看:21
本文介绍了将 ApplicationDbContext 注入 Startup 中的 Configure 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的代码:

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:无法解析范围服务来自根提供程序的ProjectName.Models.ApplicationDbContext".

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

这也是我来自 ConfigureServices 方法的代码:

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?

推荐答案

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

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.

这篇关于将 ApplicationDbContext 注入 Startup 中的 Configure 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆