Adding the DbSeeder to Startup.cs

Our next task will be to add the DbSeeder to our Startup class. Since it's a static class, we will be able to use it anywhere, but we need an instance of our ApplicationDbContext; it would be great to get that using Dependency Injection.

Theoretically speaking, we can add a new parameter in the Configure() method, as follows:

[...]

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ApplicationDbContext dbContext)
{
[...]

DbSeeder.Seed(dbContext);
}

[...]

This will indeed instantiate it through DI and get it done without drawbacks. However, we really don't want to alter the Configure method default parameter list, even if it won't affect our application.

We can achieve the same outcome in a less-intrusive fashion with a few more lines of code:

[...]

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
[...]

// Create a service scope to get an ApplicationDbContext instance
using DI

using (var serviceScope =
app.ApplicationServices.GetRequiredService<IServiceScopeFactory>
().CreateScope())

{
var dbContext =
serviceScope.ServiceProvider.GetService<ApplicationDbContext>();

// Create the Db if it doesn't exist and applies any pending
migration.

dbContext.Database.Migrate();
// Seed the Db.
DbSeeder.Seed(dbContext);
}
}

[...]

Append the highlighted snippet at the end of the Startup class Configure method, and then add an import reference to the following required namespace at the start of the Startup.cs file:

[...]
using Microsoft.Extensions.DependencyInjection;
[...]

We're now good to go.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.178.9