.NET Generic Host in ASP.NET Core

.NET Generic Host in ASP.NET Core

The ASP.NET Core templates create a .NET Core Generic Host (HostBuilder).

This topic provides information on using .NET Generic Host in ASP.NET Core. For information on using .NET Generic Host in console apps, see .NET Generic Host.

 

Host definition

A host is an object that encapsulates an app's resources, such as:

  • Dependency injection (DI)
  • Logging
  • Configuration
  • IHostedService implementations

When a host starts, it calls IHostedService.StartAsync on each implementation of IHostedService registered in the service container's collection of hosted services. In a web app, one of the IHostedService implementations is a web service that starts an HTTP server implementation.

The main reason for including all of the app's interdependent resources in one object is lifetime management: control over app startup and graceful shutdown.

Set up a host

The host is typically configured, built, and run by code in the Program class. The Main method:

  • Calls a CreateHostBuilder method to create and configure a builder object.
  • Calls Build and Run methods on the builder object.

The ASP.NET Core web templates generate the following code to create a host:

复制代码
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>();
            });
}
复制代码

The following code creates a non-HTTP workload with an IHostedService implementation added to the DI container.

复制代码
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>();
            });
}
复制代码

For an HTTP workload, the Main method is the same but CreateHostBuilder calls ConfigureWebHostDefaults:

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

If the app uses Entity Framework Core, don't change the name or signature of the CreateHostBuilder method. The Entity Framework Core tools expect to find a CreateHostBuilder method that configures the host without running the app. For more information, see Design-time DbContext Creation.

 

Default builder settings

The CreateDefaultBuilder method:

  • 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.

The ConfigureWebHostDefaults method:

The Settings for all app types and Settings for web apps sections later in this article show how to override default builder settings.

 

GenericHostBuilderExtensions.ConfigureWebHostDefaults(IHostBuilder, Action<IWebHostBuilder>) Method

Remarks

The following defaults are applied to the IHostBuilder:

  • use Kestrel as the web server and configure it using the application's configuration providers
  • configure WebRootFileProvider to include static web assets from projects referenced by the entry assembly during development
  • adds the HostFiltering middleware
  • adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true,
  • enable IIS integration

 

What is the difference between ConfigureWebHostDefaults and ConfigureWebHost methods?

Via ASP.NET Core source code, ConfigureWebHostDefaults equals to:

        public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure)
        {
            return builder.ConfigureWebHost(webHostBuilder =>
            {
                WebHost.ConfigureWebDefaults(webHostBuilder);

                configure(webHostBuilder);
            });
        }

It just calls the ConfigureWebHost, but will an additional step: ConfigureWebDefaults.

As for ConfigureWebDefaults, the source code is pretty long and placed here:

https://github.com/aspnet/AspNetCore/blob/1480b998660d2f77d0605376eefab6a83474ce07/src/DefaultBuilder/src/WebHost.cs#L280

For the difference, ConfigureWebHostDefaults configures a web host with:

  • Use Kestrel as the web server and configure it using the application's configuration providers
  • Adds the HostFiltering middleware,
  • Adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true,
  • Enable IIS integration.

Also, the official document mentioned that:

The ConfigureWebHostDefaults method 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 Kestrel web server implementation in ASP.NET Core. Adds Host Filtering middleware. Adds Forwarded Headers middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true. Enables IIS integration. For the IIS default options, see Host ASP.NET Core on Windows with IIS.

Document link: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.0#default-builder-settings

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(138)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-02-25 283. Move Zeroes
2019-02-25 DataContract with Json.Net
2019-02-25 Todo list
2019-02-25 Execution Order for the ApiController
2019-02-25 ASP.NET WEB API 2: HTTP MESSAGE LIFECYLE
2019-02-25 autofac 在webapi中拿到当前request的scope
2019-02-25 234. Palindrome Linked List
点击右上角即可分享
微信分享提示