punkouter
punkouter

Reputation: 5366

Trying to get injected service for seeding data in ASP.NET core MVC

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?

Upvotes: 2

Views: 488

Answers (1)

Jesse de Wit
Jesse de Wit

Reputation: 4177

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>();
    }
}

Upvotes: 1

Related Questions