Asp.net core source code series (1), asp. netcore

Source: Internet
Author: User
Tags webhost

Asp.net core source code series (1), asp. netcore
Preface

Asp.net core has been out for a month. I am preparing to read its source code during my spare time, and will record a series of understandings and ideas. I also hope that I can get guidance from my peers in the garden, this is just my understanding of the source code. If there are any errors, I hope you can correct them. This will be a series of articles.

 

Portal

After creating an asp.net core project, you can see a Program. cs and a Startup. cs. Today, I will focus on what Program. cs has done,

Public static void Main (string [] args) {var host = new WebHostBuilder (). useKestrel (). useContentRoot (Directory. getCurrentDirectory ()). useIISIntegration (). useStartup <Startup> (). build (); host. run ();}View Code

Here, the main method is the entry of the application. You can see that a WebHostBuilder instance object is created at the entrance, and a series of configurations are made for it, finally, execute the Build method to return an instance of the IWebHost object, and finally execute its Run and method. So far, when the application starts, what are the configurations of this series, we need to take a look at the WebHost class. We will go to github and download the source code. The link is aspnet/hosting. After downloading it, you can use VS2015 update3 to open it. First, let's take a look at the WebHostBuilder class.

WebHostBuilder

This class instance is prepared to create a WebHost class instance. Let's take a look at its constructor:

Public WebHostBuilder () {_ hostingEnvironment = new HostingEnvironment (); _ configureServicesDelegates = new List <Action <IServiceCollection> (); _ configureLoggingDelegates = new List <Action <ILoggerFactory> (); _ config = new ConfigurationBuilder (). addEnvironmentVariables (prefix: "ASPNETCORE _"). build (); if (string. isNullOrEmpty (GetSetting (WebHostDefaults. environmentKey) {// Try adding legacy envi Ronment keys, never remove these. UseSetting (WebHostDefaults. EnvironmentKey, Environment. GetEnvironmentVariable ("Hosting: Environment ")?? Environment. getEnvironmentVariable ("ASPNET_ENV");} if (string. isNullOrEmpty (GetSetting (WebHostDefaults. serverUrlsKey) {// Try adding legacy url key, never remove this. useSetting (WebHostDefaults. serverUrlsKey, Environment. getEnvironmentVariable ("ASPNETCORE_SERVER.URLS "));}}View Code

This method initializes some basic variables, _ hostingEnvironment (host environment configuration, including the Environment name, application name, webroot path, and ContentRoot path ), _ configureServicesDelegates (a set of service operation delegation in terms of name), _ configureLoggingDelegates (a set of log operation delegation in terms of name ), _ config (configure an instance of the Creator), and then write two configurations ("environment" and "urls") into _ config ").

Then call the extension method UseKestrel (). Let's look at the Code:

Public static IWebHostBuilder UseKestrel (this IWebHostBuilder hostBuilder) {return hostBuilder. configureServices (Action <IServiceCollection>) (services => {ServiceCollectionServiceExtensions. addTransient <IConfigureOptions <KestrelServerOptions>, KestrelServerOptionsSetup> (services); ServiceCollectionServiceExtensions. addSingleton <IServer, KestrelServer> (services );}));}View Code

This method calls the ConfigureServices method of WebHostBuilder and adds some delegate processing methods for Kestrel to the host, these delegate methods include adding Kestrel and some of its configuration options to the Service Processing set of the application.

Call UseContentRoot (Directory. GetCurrentDirectory (). Let's look at the Code:

Public static IWebHostBuilder UseContentRoot (this IWebHostBuilder hostBuilder, string contentRoot) {if (contentRoot = null) throw new ArgumentNullException ("contentRoot"); return hostBuilder. useSetting (WebHostDefaults. contentRootKey, contentRoot );}View Code

This extension method still calls UseSeeting () to add the configuration item "contentRoot" to _ config configuration (For details, refer to the link). The value is the current directory.

Then call the extension method UseIISIntegration (). Let's look at the Code:

Public static IWebHostBuilder UseIISIntegration (this IWebHostBuilder app) {if (app = null) throw new ArgumentNullException ("app"); string str1 = app. GetSetting (WebHostBuilderIISExtensions. ServerPort )?? Environment. GetEnvironmentVariable (string. Format ("ASPNETCORE _ {0}", (object) WebHostBuilderIISExtensions. ServerPort); string str2 = app. GetSetting (WebHostBuilderIISExtensions. ServerPath )?? Environment. GetEnvironmentVariable (string. Format ("ASPNETCORE _ {0}", (object) callback. ServerPath); string pairingToken = app. GetSetting (WebHostBuilderIISExtensions. PairingToken )?? Environment. GetEnvironmentVariable (string. Format ("ASPNETCORE _ {0}", (object) WebHostBuilderIISExtensions. PairingToken); if (! String. IsNullOrEmpty (str1 )&&! String. IsNullOrEmpty (str2 )&&! String. IsNullOrEmpty (pairingToken) {string str3 =" http://localhost : "+ Str1 + str2; app. useSetting (WebHostDefaults. serverUrlsKey, str3); hostingtransferactionswebhostbuilderextensions. captureStartupErrors (app, true); app. configureServices (Action <IServiceCollection>) (services => {ServiceCollectionServiceExtensions. addSingleton <IStartupFilter> (services, (IStartupFilter) new IISSetupFilter (pairingToken); OptionsServiceCollectionExtensions. configure <ForwardedHeaders Options> (services, (Action <ForwardedHeadersOptions>) (options => {options. ForwardedHeaders = ForwardedHeaders. XForwardedFor | ForwardedHeaders. XForwardedProto; bool flag =! String. IsNullOrEmpty (Environment. GetEnvironmentVariable ("WEBSITE_INSTANCE_ID"); options. requireheaderpolicry =! Flag ;})) ;}) ;}return app ;}View Code

Here we mainly configure IIS. I understand that IIS will forward the requests it listens to Kestrel for processing, so the real listening is still in IIS, of course, this step can also be omitted directly, with Kestrel directly listening for port requests. Comment out the call to this method and start the application to directly access localhost: 5000 (you can try it ).

Next is the UseStartup <Startup> () method. This method and the Startup class will be explained separately in the next article, mainly set the processing module of Aspnet core (here we are processing MVC)

Finally, the Builder () method:

Public IWebHost Build () {// Warn about deprecated environment variables if (Environment. GetEnvironmentVariable ("Hosting: Environment ")! = Null) {Console. writeLine ("The environment variable 'hosting: Environment 'is obsolete and has been replaced with 'aspnetcore _ ENVIRONMENT'");} if (Environment. getEnvironmentVariable ("ASPNET_ENV ")! = Null) {Console. writeLine ("The environment variable 'aspnet _ env' is obsolete and has been replaced with 'aspnetcore _ ENVIRONMENT '");} if (Environment. getEnvironmentVariable ("ASPNETCORE_SERVER.URLS ")! = Null) {Console. writeLine ("The environment variable 'aspnetcore _ SERVER. URLS 'is obsolete and has been replaced with 'aspnetcore _ urls' ");} var hostingServices = BuildHostingServices (); var hostingContainer = hostingServices. buildServiceProvider (); var host = new WebHost (hostingServices, hostingContainer, _ options, _ config); host. initialize (); return host ;}View Code

This method generates the final host of an application based on the previously registered series of services (listener service, Log service, etc.) and configurations, and initialize it (the call and creation method source code inside is clear ). Another very important method, BuildHostingServices (), returns a ServiceCollection instance, but I haven't figured out what this instance is, my test should be some service configuration items, and finally call the WebHost constructor to generate a WebHost instance object.

Then, call the host. run () method to start the service. The specific call to the run method will be analyzed in a separate chapter.

Other methods

1. UserUrls (),

Public static IWebHostBuilder UseUrls (this IWebHostBuilder hostBuilder, params string [] urls) {if (urls = null) throw new ArgumentNullException ("urls"); return hostBuilder. useSetting (WebHostDefaults. serverUrlsKey, string. join (hostingtransferactionswebhostbuilderextensions. serverUrlsSeparator, urls ));}View Code

 

This method uses the UseSetting () method to set the "urls" value in the configuration file _ config.

2. UseConfiguration (),

Public static IWebHostBuilder UseConfiguration (this IWebHostBuilder hostBuilder, IConfiguration configuration) {foreach (KeyValuePair <string, string> keyValuePair in ConfigurationExtensions. asEnumerable (configuration) hostBuilder. useSetting (keyValuePair. key, keyValuePair. value); return hostBuilder ;}View Code

Set parameters and values in _ config by specifying the configuration file

3.

Summary

This article only gives a systematic description of how to create a host object. There are many specific implementations in it. I have not seen them yet. I feel that every method has many things, I will gradually improve my understanding, and I hope you can point it out. May the. NET ecosystem be better and better, and everyone will work together. Recommend a URL

There is an online discussion about aspnet.

 

If you feel helpful to you, please recommend it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.