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)
I'm using ASP.NET Core 2.0 with the default options.
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: 'Cannot resolve scoped service
'SGDTP.Infrastructure.Context.SGDTPContext' from root
provider.'
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…