ASP.NET Hosting Models

Çağlar Can SARIKAYA
2 min readFeb 24, 2024

--

I saw a code on the program.cs It starts like that

var hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.ConfigureServices((builder, services) =>
{
services.Configure<AppConfig>(builder.Configuration.GetSection("ApplicationSettings"));

services.AddHttpClient<IGoogleNewsRssService, GoogleNewsRssService>();
services.AddSingleton<IGoogleSheetsService, GoogleSheetsService>();
});


using var host = hostBuilder.Build();
await host.StartAsync();

I wonder about what is Host?

There are 3 different hosting models on .net applications developments. IHost, IWebHost and WebApplication.

IWebHost -> this one is started Asp.net core 2.0 we use that interface for managing web applications HTTP servers, defining middlewares and life cycles. We use WebHostBuilder with IWebHost for configurations.

public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}

IHost -> It came on .net core 3.0 and it includes IWebHost and additionally, we can use these web applications and unweb apps. We use that with the ConfigureWebHostDefaults method on IHostBuilder. Mostly used on console applications

public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}

WebApplication -> It came on .Net 6 and it included IHost and IWebHost. Use and understand this much easier than the old ones. It supports minimal API's

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Run();
  • WebHost: Specifically used in .NET Core 2.x and 3.x versions to configure and start web applications. It is used for web server configurations like Kestrel.
  • IHost: In .NET Core 3.0 and later, it serves as a general application container, including for non-web background services. Web features are added with ConfigureWebHostDefaults.
  • WebApplication: In .NET 5 and later, it simplifies the functionality of IHost and WebHost with a streamlined API. It is ideal for configuring applications without a Startup class and for minimal APIs.

--

--