In ConfigureServices I say
services.AddDbContext<PwdrsDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("PwdrsDbConnection"));
});
RegisterServices(services);
In configure I say
SeedData.SeedDatabase(app);
In the static seed method I say
public class SeedData
{
public static void SeedDatabase(IApplicationBuilder app)
{
PwdrsDbContext context = app.ApplicationServices.GetService<PwdrsDbContext>();
}
}
and when I run it says
Cannot resolve scoped service 'Pwdrs.Infra.Data.Context.PwdrsDbContext' from root provider
I need the dbcontext to seed the data but what am I missing?
You need to inject the services from your ConfigureServices method into the Configure
method separately:
public void Configure(
IApplicationBuilder app,
IServiceProvider services) // <- magic here
{
// ...
SeedData.SeedDatabase(services);
}
public class SeedData
{
public static void SeedDatabase(IServiceProvider services)
{
PwdrsDbContext context = services.GetRequiredService<PwdrsDbContext>();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.