asp.net core 3.x general principle and the host

I. Introduction

But generally speaking the principle of universal asp.net core 3.x host, these things are by looking at the source code and according to their own lessons learned come, in the article will not go into the source code, because you know personally feel that to understand the principle of extension points, hit late At that time there needs to carefully study the source code too late.
Before reading you should first understand the next ( Recommended blog A garden of the old blog ):

  • asp.net core in dependency injection,
  • Configuration,

To explain the approach is:

  1. Outline
  2. About each of the core classes and expansion mode
  3. How do we usually use
  4. to sum up

Second, an overview

Previous console application, main winform is first executed when the program starts, follow all our own code to implement the stuff on the framework and business, for example, we want to use the configuration on ConfigurationManager.AppSettings ... If you want to use dependency injection the need to introduce third-party frameworks, such as autofact. asp.net framework similar era

In previous versions of .net core 3.0 is used by default is IWebHost, it defines the internal settings IOC container (registered service reflected in Startup.ConfigServices), and various configurations sources (reflected in the Program to configure the host), we follow Controler , View, including business code can easily do dependency injection and configuration information (including the use of option mode)

Sometimes we want to write a service, but this service is not used for api / web, handling http requests, such things want to be a back-end collection service, has been waiting for remote hardware devices submit data in real time over, the back-end for processing. But it is desirable to use the configuration asp.net core provided dependency injection, logs, and other functions. Later, Microsoft will asp.net core of this stuff pulled out, called generic host, used to carry any service, these custom services can be very easy to use configuration, dependency injection, logs, and other functions. Now asp.net core carried by only one universal host service.

2.1, the main idea of ​​the realization of default is:

2.1.1, the definition (Microsoft-defined):

  • Define HOST, which includes life cycle events IOC root container, host and application of the definition given, IHostedService collection (an instance is called a service or application, asp.net core is one such example)
  • It allows the caller to provide a bunch of delegate registration services to the IOC, and "Configuration Source" and set the host application
  • Provides a method to add an object that implements the IHostedService to the host
  • The corresponding event allows the caller to register the host application and trigger the start and stop phase

2.1.2 configuration (our code, Microsoft has defined a lot of helper methods):

  • Creating IHost examples
  • Host registration services to the IOC container
  • Configuring the host and applications "configuration source
  • Add IHostedService example to the internal host (that is, our ultimate service)
  • Host and application life cycle events, to achieve some special tasks

2.1.3, start-up phase (Microsoft-defined)

  • Above the so-called basic configuration is achieved through the commission (usually a variety of extension methods provided by Microsoft is the ultimate execution of a delegate), which commissioned the callback to set "Configuration Source" and registration services
  • Finally traversal start HostedService
  • During startup will callbacks corresponding lifecycle events

2.2, what is the application?

The above mentioned several "applications" and now for the host asp.net core framework is an application, for example we said above, "Things back-end service" is another application. From the code, it is the realization of a IHostedService.
And host applications to many relationship, a plurality of host applications can share information, such as: IOC container host, the host configuration. Application configuration. Of course, you can also use to create their own IOC container and root configuration object

Host configuration and application configuration relationship? These two configuration objects are present in the Host, host configuration is only associated with the configuration of the host, the host application configuration is shared by multiple applications configuration, if the host is only one application, you can take it for final application configuration . Additionally comprising application configuration Host Configuration

Note: Keep in mind in interpreting our present purpose is to explain the generic host, which means you can carry hosting your own definition of what mvc action routing the controller Do not think about the class

Third, core classes

The following describes the host several core default implementation class, almost every class has a corresponding interface, in order to shorten the length of the interface to facilitate the understanding not speak.

3.1、Host

It represents the host, the host used (bearers) We apply (a IHostedService to achieve).
Mainly includes: life cycle event log, host and application options object IOC root container, the host, stop start / stop method.
Interface defines only: IOC root containers + Start + Stop method
it is created, configured and started in the Program.Main

The default implementation Microsoft.Extensions.Hosting.Internal.Host, it is an internal class that is activated when the host in the future:

  • WaitForStartAsync trigger event host
  • One by one to start the host is not tired of hostedService
  • Trigger _applicationLifetime .NotifyStarted ();? Events
  • Conversely when it stops, the first one by one stop hostedService, triggered in response to events, and finally stop the host

Extended:

Host is because the default internal modified, it can not inherit

  • Custom implementation IHost; (this is not to say, you can be arbitrary)
  • Subscribe to the host application and life cycle events (realized IHostLifetime, IHostApplicationLifetime and added to the IOC container)

Mode 2 is easier to implement in most cases are more common

To mention a mouth, asp.net the default host core 3.x is now used only did a root web-related configuration, the next one will explain

3.2、HostBuilder

Host duties just finished some features of the host, then it's best to create and configure another to define a class HostBuilder, it is Host's creator (factory), we usually

  • At system startup (Program.Man) create HostBuilder,
  • And configure (to the IOC container registration service, set the "Configuration Source" hosts and applications),
  • Finally, call the Build method to generate our ultimate Host

First IHostBuilder source through the interface can be seen that it provides the following functions slightly (by way of delegation)

  • Set the host application and the "Configuration Source"
  • Configure an IOC container itself
  • IOC container like to add services
  • According to later create Host Configuration
  • Properties have a property, a type of dictionaries, data may be communicated in a plurality of steps for constructing Host

Extended:

For our users, it is mainly through its stuffed inside a variety of methods to delegate, in order to achieve the "configuration source" IOC containers registration service and set the host and application
can be but rarely is estimated to achieve IHostBuilder host; inheritance HostBuilder not be very meaningful, because it does not provide an abstract and virtual methods

Default Build process
initialization host configuration object IConfiguration, mainly callback, the host does not do other
initialization host environment object _hostingEnvironment

  • Application name from the host configuration in the previous step
  • Environmental name (development? Debugging?) To configure time, if not the default mode of production is "Production"
  • Content roots also came from a configuration where it is if there is no current program path
  • According to a ContentRootFileProvider implementation class with content creation is PhysicalFileProvider

Initialization HostBuilderContext, created according to the above configuration and environment of this context (used here only temporarily host configuration, the following will be replaced with the configuration application)
Initialization Configuration

  • In the above contents of the root (This property is required in the future if the physical file provided as configuration source) arranged to find a root
  • The host configuration stuffed this application configuration, the application configured configuration + = Host Configuration callback
  • Finally Configuration replace HostBuilderContext for this configuration objects

Creating IOC container

  • Creating ServiceCollection, and above several objects to put into simple interest mode
  • Also put IHostApplicationLifetime and IHostLifetime and Host
  • On Option mode, registration log
  • Callback configureServicesAction
  • Call the factory _serviceProviderFactory create ServiceProvider
  • Callback _configureContainerActions
  • Finally, return container

Calls vessel parsed and return Host

3.3, HostBuilder factory method Host.CreateDefaultBuilder

With the above Host, has also been a corresponding creator HostBuilder, why should it then provides a factory method?
Because the principle of separation of duties, Host application and provides only responsible for carrying containers and configuration source; HostBuilder only responsible for the configuration and create Host, provide some default value as possible (when provided the caller does not provide those parameters in the future). At this point we can directly use HostBuilder Host and start to create it, but do not forget .net core is a generic framework should provide a more concise way to create the ultimate Host, it provides static methods Host.CreateDefaultBuilder, it provides more possible default values, core tasks are as follows:

  • new HostBuilder
  • Current directory setup for the content root
  • For the host configuration settings as a configuration environment variable source (prefix DOTNET_ only concerned with environment variables)
  • Application configuration settings "appsettings.json" and as the configuration source "appsettings {env.EnvironmentName} .json."; Also the environment variable added to the configuration of the source application; finally added to the command line parameters configuration source
  • Configuring Log
  • If the development model, but also to verify the configuration dependent injection range

Fourth, from the user's point of view

To achieve our service through a custom implementation IHostedService class, our class of service

  • Direct use dependency injection,
  • May be arranged to get the host application and the global configuration object dependency injection, or more convenient to use a further option mode
  • We can also inject logger
  • Because data from the host into the creation of almost all the IOC container, so we can get through dependency injection
  • other...

Called Program.man Host.CreateDefaultBuilder, if necessary, provide the appropriate commission to register "Configuration Source" and set the host and application services, preferably through the relevant extension methods and custom extension methods. Key to remember into our own service implementation class

V. Summary

.net core provides a new bearing applications (including but not limited asp.net core) for our way -> generic host, through which we can easily be used in their application dependency injection, configuration, logs, you can use your imagination to realize a lot of cow B frame.
asp.net core 3.x default is to start using it to carry the
core of the Host, HostBuilder, Host.CreateDefaultBuilder to achieve a common host, and provides extension points

Finally, I want to say that if a default aop program on the .net core even more perfect.
Next try under asp.net said core is how to carry on a common host

 

Guess you like

Origin www.cnblogs.com/jionsoft/p/12154519.html