IHost is the built, runnable application produced by an IHostBuilder. In an ASP.NET Core app, it contains the HTTP server and the services and configuration needed to handle requests. A worker service can use the same generic host without handling HTTP requests. section 30.2 section 34.4
A typical ASP.NET Core setup separates host construction from application features:
- Program.cs creates an IHostBuilder, calls Build() to produce the IHost, then calls Run(). section 30.2
- ConfigureWebHostDefaults() sets up web hosting; UseStartup<Startup>() identifies the class that configures services, middleware, and endpoints. section 30.5 section 30.7
- Startup.cs holds features likely to change as the application grows, while Program.cs generally holds host setup. section 30.1 section 30.2
Build and run a web host
A small Program.cs can use `Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()).Build().Run();`. The builder defines the setup; Build() creates the IHost; Run() starts it. section 30.2
Host.CreateDefaultBuilder() supplies initial configuration, logging, hosting-environment, and dependency-injection settings. Customize those defaults when needed—for example, add a logging provider or replace configuration sources—rather than building every setting from scratch. Keep the content root, where application files are found, distinct from the web root used for publicly accessible static files. section 30.4 section 30.7
Listing 34.7 Program.cs for a worker service that saves exchange rates using EF Core
using Microsoft.EntityFrameworkCore;
IHost host = Host.CreateDefaultBuilder(args) #1
.ConfigureServices((hostContext, services) => #2
{
services.AddHttpClient<ExchangeRatesClient>(); #3
services.AddHostedService<ExchangeRatesHostedService>(); #3
var connectionString = hostContext.Configuration #4
.GetConnectionString("SqlLiteConnection")) #4
services.AddDbContext<AppDbContext>(options => #5
options.UseSqlite(connectionString)); #5
})
.Build(); #6
host.Run(); #7
This worker-service Program.cs shows the non-HTTP variation: register services with ConfigureServices(), build an IHost, and run it. section 34.2.1
For most new ASP.NET Core web apps, minimal hosting with WebApplication is simpler. The generic-host approach remains useful for an existing Startup-based app, finer control over construction, or a non-HTTP worker. Its tradeoff is more bootstrapping complexity, including configuration spread across Program.cs and Startup.cs. section 30.6 section 30.5
