Hosting - mcbride-clint/DeveloperCurriculum GitHub Wiki
When restructuring .Net for .Net Core, Microsoft factored all their application projects to start from the same base code, a Console App. From there the application will build up needed functionality. The first thing an application will do is create a HostBuilder object that will define the boundaries and features of the application.
The HostBuilder follows the builder pattern so additional features can be added to the object, usually via Fluent syntax (commands strung together by .), before calling .Build()
to construct an instance of the Host
class.
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>();
});
}
A host is an object that encapsulates an app's resources, such as:
- Dependency Injection (DI)
- Logging
- Configuration
- IHostedService implementations
- Sets the content root to the path returned by GetCurrentDirectory.
- Loads host configuration from:
- Environment variables prefixed with DOTNET_.
- Command-line arguments.
- Loads app configuration from:
- appsettings.json.
- appsettings.{Environment}.json.
- User secrets when the app runs in the Development environment.
- Environment variables.
- Command-line arguments.
- Adds the following logging providers:
- Console
- Debug
- EventSource
- EventLog (only when running on Windows)
- Enables scope validation and dependency validation when the environment is Development.
- Loads host configuration from environment variables prefixed with ASPNETCORE_.
- Sets Kestrel server as the web server and configures it using the app's hosting configuration providers. For the Kestrel server's default options, see * Configure options for the ASP.NET Core Kestrel web server.
- Adds Host Filtering middleware.
- Adds Forwarded Headers middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED equals true.
- Enables IIS integration. For the IIS default options, see Host ASP.NET Core on Windows with IIS.
Seeing the usefulness of Host
encapsulation, Microsoft created the Microsoft.Extensions.Hosting
and other Extensions as .Net Standard compliant so .Net Framework and .Net Core+ can utilize them effectively.
Hosting, in particular, can be used effectively in Console Apps in the same style as above to gain the full benefits.
Usage in other project types, such as Web Forms or MVC, is quite limited as they have their own project startup procedures and encapsulation procedures.
- Microsoft Docs - .Net Generic Host - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-5.0
- Pluralsight - Building Configurable Applications - https://app.pluralsight.com/library/courses/building-configurable-applications-dot-net-generic-host/table-of-contents