.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?
IntermediateAnswer
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.