Advertisement
Intermediate .NET, Generic Host

How do you access the built IHost's service provider after Build() to resolve services outside the normal request/injection flow, such as in Program.cs itself?

Short answer

After calling builder.Build(), the resulting IHost exposes a Services property (an IServiceProvider) that Program.cs or other top-level startup code can use to resolve services directly -- commonly used for running one-time startup logic like applying database migrations or…

Save .NET mock interview
Advertisement
AModel answer
After calling builder.Build(), the resulting IHost exposes a Services property (an IServiceProvider) that Program.cs or other top-level startup code can use to resolve services directly -- commonly used for running one-time startup logic like applying database migrations or seeding initial data before calling host.Run().
var host = builder.Build();

using (var scope = host.Services.CreateScope()) {
    var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    await db.Database.MigrateAsync();  // one-time startup migration
}

host.Run();
Real-world example
A Worker Service's Program.cs resolves a scoped DbContext once at startup (via a manually created scope) to apply pending EF Core migrations automatically before the application begins processing any background work.
Likely follow-ups
  • Why is a manually created scope needed here instead of just calling GetRequiredService directly on host.Services?
  • What are the risks of running migrations automatically at every startup versus as a separate deployment step?
Related topics