Generic host and Web host in .Net Core
This topic provides information on using .NET Generic Host
and Web host
in ASP.NET Core application. As name suggests Web host can be used only
for HTTP (eg tied for web application) only but generic host, which has been introduced in .Net core 3.0, can be used for Console application as well.
Though the Generic host got included in .NET core 2.1 it was only used for non HTTP workloads. In .NET Core 3.0 it became a universal standard (HTTP + non HTTP workloads).
Host definition
A host is an object that encapsulates an app's resources, such as:
Set up a host
The host
is typically configured, built, and run by code in the Program class. The Main method:
CreateDefaultBuilder()
method to create and configure a builder object.
Build()
to create an IHost instance.
Run
or RunAsync
method on the host object.
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); }); }
To call Startup
Class from CreateHostBuilder
you can write below code:
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
We can do above by using WebHostBuilder
:
public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup() .Build(); host.Run(); }
To create a Host we can use the new HostBuilder, which has a similar set of methods and extensions as the existing
WebHostBuilder
.There is one main difference to be aware of and that is 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 the final service provider.
WebHostBuilder has now been deprecated and could be removed in the near future.
Reason to use ConfigureWebHostDefaults
is that the new host builder is a
Generic Host Builder so it is important to tell that we intend to configure the default settings for a Web Host.
The CreateDefaultBuilder()
method performs a lot of “magic” behind the scenes, by making use of pre-configured defaults.
From the official documentation, here is a summary of the default configuration from the Default Builder:
Summary
To summarise, we looked at what makes the Generic Host
generic (for non-HTTP) and what is limitations of
Web Host
(can not be used for Console app). Hope you picked up a thing or two.
Cheers!