无法在ASP.NET Core 2.0中解析DbContext [英] Cannot resolve DbContext in ASP.NET Core 2.0

查看:169
本文介绍了无法在ASP.NET Core 2.0中解析DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我正在尝试为我的数据库添加示例数据.我已经读到这是做到这一点的方法(在 Startup.Configure 中)(请参阅

First of all, I'm trying to seed my database with sample data. I have read that this is the way to do it (in Startup.Configure) (please, see ASP.NET Core RC2 Seed Database)

我使用带有默认选项的ASP.NET Core 2.0.

I'm using ASP.NET Core 2.0 with the default options.

和往常一样,我在ConfigureServices中注册我的DbContext. 但是之后,在Startup.Configure方法中,当我尝试使用GetRequiredService解析它时,它会显示以下消息:

As usual, I register my DbContext in ConfigureServices. But after that, in the Startup.Configure method, when I try to resolve it using GetRequiredService, it throws with this message:

System.InvalidOperationException:'无法解析作用域服务 根目录中的"SGDTP.Infrastructure.Context.SGDTPContext" 提供者."

System.InvalidOperationException: 'Cannot resolve scoped service 'SGDTP.Infrastructure.Context.SGDTPContext' from root provider.'

我的Startup类是这样的:

My Startup class like this:

public abstract class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<SGDTPContext>(options => options.UseInMemoryDatabase("MyDatabase"))
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

        SeedDatabase(app);
    }

    private static void SeedDatabase(IApplicationBuilder app)
    {
        using (var context = app.ApplicationServices.GetRequiredService<SGDTPContext>())
        {
            // Seed the Database
            //... 
        }
    }
}

我做错了什么? 另外,这是创建种子数据的最佳位置吗?

What am I doing wrong? Also, is this the best place to create seed data?

推荐答案

您正在将SGDTPContext注册为作用域服务,然后尝试在外部中访问它一个范围.要在您的SeedDatabase方法中创建作用域,请使用以下命令:

You're registering SGDTPContext as a scoped service and then attempting to access it outside of a scope. To create a scope inside your SeedDatabase method, use the following:

using (var serviceScope = app.ApplicationServices.CreateScope())
{
    var context = serviceScope.ServiceProvider.GetService<SGDTPContext>();

    // Seed the database.
}

使用@khellang指出注释中的CreateScope扩展方法,并使用@Tseng的注释和 answer 关于如何在EF Core 2中实施播种.

Credit to @khellang for pointing out the CreateScope extension method in the comments and to @Tseng's comment and answer re how to implement seeding in EF Core 2.

这篇关于无法在ASP.NET Core 2.0中解析DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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