Dependency Injection of an Entity Framework Context within Program.cs Using Top Level Statements

I was working on Entity Framework recently, and I wanted to make sure that the database existed and was seeded before I executed any controller methods.

In the time before top-level statements, I would have used the Configure(..) method in Startup.cs to do this, passing the EF context as a parameter to the method. But that is not the case anymore. I needed to use the EF Context from my service collection in Program.cs.

 1using Microsoft.EntityFrameworkCore;
 2using WebApiEntityFrameworkDockerSqlServer.Data;
 3
 4var builder = WebApplication.CreateBuilder(args);
 5
 6builder.Services.AddControllers();
 7
 8builder.Services.AddDbContext<SomeContext>(options =>
 9    options.UseSqlServer(builder.Configuration.GetConnectionString("MyDatabase")));
10
11var app = builder.Build();
12
13// get the context from the service collection
14using(var scope = app.Services.CreateScope())
15{
16    var someContext = scope.ServiceProvider.GetRequiredService<SomeContext>();
17    someContext.Database.EnsureCreated();
18    someContext.Seed();
19}
20
21app.UseAuthorization();
22
23app.MapControllers();
24
25app.Run();
comments powered by Disqus

Related