9

In a .NET 5 web application, we use code such as the following in startup.cs to initialize the DB using Entity Framework:

using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
    var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
    context.Database.EnsureCreated();
}

In .NET 6 though, I get the error that there is no ApplicationServices. I tried the solution proposed here, but then I get a runtime error: 'Cannot resolve scoped service 'WebApplication1.DataAccess.SchoolDbContext' from root provider'. The complete code in my program.cs is as follows:

using WebApplication1.DataAccess;
using Microsoft.EntityFrameworkCore;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Configuration.AddJsonFile("appsettings.json");
builder.Services.AddRazorPages();

// Setup EF connection
// https://stackoverflow.com/a/43098152/1385857
// https://medium.com/executeautomation/asp-net-core-6-0-minimal-api-with-entity-framework-core-69d0c13ba9ab
builder.Services.AddDbContext<SchoolDbContext>(options => 
        options.UseSqlServer(builder.Configuration["Data:SchoolLocal:ConnectionString"]));

WebApplication app = builder.Build();

// https://stackoverflow.com/a/71258326/1385857
SchoolDbContext dbcontext = app.Services.GetRequiredService<SchoolDbContext>();
dbcontext.Database.EnsureCreated();
...

Help would be great.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Manish
  • 1,726
  • 3
  • 23
  • 29

2 Answers2

19

WebApplication returned by builder.Build() has Services property which allows to create a scope:

using(var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<SchoolDbContext>();
    // use context
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
3

You can also use the async version of the CreateScope() method. If you want to call an awaitable method.

using(var scope = app.Services.CreateAsyncScope())
{
  var dbContext = scope.ServiceProvider.GetRequiredService<SchoolDbContext>();
  //more codes ...
}