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

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.

主站蜘蛛池模板: 湘乡市| 罗城| 汾阳市| 色达县| 陆丰市| 开江县| 田东县| 儋州市| 泰兴市| 临邑县| 抚宁县| 天峨县| 赤城县| 正阳县| 交口县| 浠水县| 蕉岭县| 马边| 旬邑县| 侯马市| 昌邑市| 永新县| 怀化市| 仲巴县| 崇礼县| 巴林左旗| 淮阳县| 宝兴县| 仁怀市| 兴仁县| 屏南县| 永宁县| 邵东县| 东乡族自治县| 榆社县| 曲周县| 化州市| 西乌珠穆沁旗| 栾城县| 德安县| 广东省|