无法在ASP.NET Core 2.0中解析DbContext

Sup*_*JMN 32 .net c# asp.net entity-framework asp.net-core

首先,我正在尝试使用示例数据为我的数据库设定种子.我已经读过这是这样做的方法(在Startup.Configure中)(请参阅ASP.NET Core RC2种子数据库)

我正在使用ASP.NET Core 2.0和默认选项.

像往常一样,我注册了我DbContextConfigureServices.但在那之后,在Startup.Configure方法中,当我尝试使用GetRequiredService它解决它时,它抛出此消息:

System.InvalidOperationException:'无法从根提供程序解析作用域服务'SGDTP.Infrastructure.Context.SGDTPContext'.

我的Startup类是这样的:

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
            //... 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Kir*_*kin 65

您正在注册SGDTPContext为范围服务,然后尝试在范围之外访问它.要为您的目的创建范围,可以使用以下解决方案:

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

    // Seed the database.
}
Run Code Online (Sandbox Code Playgroud)

这是一个讨论这种方法的旧Github 问题.

感谢@khellang指出SeedDatabase他评论中的扩展方法.

请参阅@ Tseng的评论和答案,了解如何最好地处理EF Core 2中的种子数据.

  • _does似乎仍然是我所看到的播种的推荐方法_嗯,不完全是.使用scoped yes,但不在Configure方法内部,使用EF Core 2.0在设计时进行DbContext的发现和实例化的方式.有关当前推荐的方法,请参阅/sf/answers/3215941851/.如果不断在`Configure`方法做播种,然后运行`DOTNET EF migrations`或`DOTNET EF数据库update`也将执行播种,有些东西你几乎运行命令行工具时,不希望 (2认同)
  • 仅供参考;直接在`IServiceProvider`上有[CreateScope扩展方法](https://github.com/aspnet/DependencyInjection/blob/88c3bd6fe2786dd759b4a6c6d7c410e895336b6c/src/DI.Abstractions/ServiceProviderServiceExtensions.cs#L120-L128),因此您可以剪切`.GetRequiredService &lt;IServiceScopeFactory&gt;()`,然后直接调用它即可:) (2认同)