官术网_书友最值得收藏!

Understanding the generic host

Starting with version 3.0, ASP.NET Core is now bootstrapped using a generic host. This means that it is not tied specifically to HTTP or any other web protocol, but it potentially supports any kind of protocol, including low-level TCP. The templates have changed and now the bootstrap looks something like this:

Host
.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

We are now using the Host class to create an instance of a class that implements IHostBuilder, not IWebHostBuilder, although the result is the same.

We can interfere in the bootstrap process by means of extension methods. Specifically, we can configure the following:

  • Services registration
  • Logging
  • Configuration
  • Web hosting defaults (host, startup class)

Here is a full example of changing the configuration:

Host
.CreateDefaultBuilder(args)
.ConfigureHostConfiguration(builder =>
{
//host configuration (Kestrel or HTTP.sys)
builder.Properties["key"] = "value";
})
.ConfigureAppConfiguration(builder =>
{
//app configuration
builder.Add(new JsonConfigurationSource { Path =
"./configuration.json", Optional = true });
builder.Properties["key"] = "value";
})
.ConfigureLogging(builder =>
{
//add logging providers
builder.AddConsole();
})
.ConfigureServices(services =>
{
//register services
services.AddSingleton<IMyService, MyService>();
})
.ConfigureWebHostDefaults(webBuilder =>
{
builder.ConfigureKestrel(options =>
{
//set Kestrel options
});

//set the startup class
webBuilder.UseStartup<Startup>();
})

It normally doesn't make sense to change the IHostLifetime of the application, because this is tied to the type of the application we're building. The options we have are as follows:

  • ConsoleLifetime: The default, cross-platform host; listens to CTRL-C and SIGINT, SIGTERM signals for stops
  • SystemdLifetime: For operating systems that use systemd, such as MacOS and Linux; listens to SIGTERM signals
  • WindowsServiceLifetime: Only for Windows; listens to Windows service events

It is the host's responsibility to call the IHostApplicationLifetime events when the application has finished loading, is about to stop, or has stopped. You can read about it in Chapter 18, gRPC and Other Topics.

Services registered in ConfigureServices will be available to be injected into the Startup class's constructor, and will also be present in the services parameter passed to its ConfigureServices method. The same goes for the logging providers and to the app configuration. Next, let's move on to the MVC pattern.

主站蜘蛛池模板: 平安县| 唐河县| 乌拉特后旗| 崇礼县| 昌乐县| 昭苏县| 云梦县| 石景山区| 临清市| 前郭尔| 木里| 台安县| 永德县| 历史| 诏安县| 高要市| 鹤山市| 石渠县| 措美县| 夏河县| 饶阳县| 肃宁县| 师宗县| 花莲市| 大庆市| 兴国县| 新乐市| 四会市| 十堰市| 三穗县| 舞钢市| 晋州市| 修武县| 恩施市| 桓台县| 宜章县| 衡水市| 利津县| 靖西县| 开原市| 凤冈县|