ASP.NET Core Web Host
The host or web host in ASP.NET is responsible for app startup and lifetime management. At a minimum, the host configures a server and a request processing pipeline. The host can also set up logging, dependency injection, and configuration
Set up a host
Create a host using an instance of IWebHostBuilder
. This is typically performed in the app's entry point, the Main method.
public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup(); }
The code that calls CreateDefaultBuilder is in a method named CreateWebHostBuilder, which separates it from the code in Main that calls Run on the builder object.
CreateDefaultBuilder Roles
CreateDefaultBuilder has many roles in ASP.Net core:
The WebHostBuilder also allows us to load configuration from multiple sources into a final configuration representation of Key/Value pairs.
public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup() .Build(); host.Run(); } }
So why WebHostBuilder if CreateDefaultBuilder is there?
There is one main difference to be aware of. The HostBuilder doesn’t provide an extension method that allows you to use a startup class as we can with the WebHostBuilder. This decision was made primarily to avoid the need to create two separate DI containers behind the scenes. With the generic host, a single service collection is configured and then used to build a the final service provider.
The works extremely well for ASP.NET Core web applications, but there were no similar options in the framework for other types of application, until now!