写在前面

asp .net core中的通用主机构建器是在v2.1中引入的,应用在启动时构建主机,主机作为一个对象用于封装应用资源以及应用程序启动和生存期管理。其主要功能包括配置初始化(包括加载配置以及配置转换为通用的键值对格式),创建托管环境和host通用上下文、依赖注入等。

在.net core 3.0中采用了ihostbuilder用于创建host,同时也不再建议使用web主机,而建议使用泛型主机,主要原因是原有的通用主机仅适用于非http负载,为了提供更加广泛的主机方案,需要将http管道与web主机的接口分离出来。但web主机仍会向后兼容。

.net core 3.0中创建通用主机

以下代码是v3.0中提供的模板代码,可以看到在创建主机的过程中,已经摒弃了webhostbuilder的创建方式

   1:  public class program
   2:  {
   3:      public static void main(string[] args)
   4:      {
   5:          createhostbuilder(args).build().run();
   6:      }
   7:   
   8:      public static ihostbuilder createhostbuilder(string[] args) =>
   9:          host.createdefaultbuilder(args)
  10:              .configurewebhostdefaults(webbuilder =>
  11:              {
  12:                  webbuilder.usestartup<startup>();
  13:              });
  14:  }

而在.net core 2.x中

   1:  public class program
   2:  {
   3:     public static void main(string[] args)
   4:     {
   5:        createwebhostbuilder(args).build().run();
   6:     } 
   7:   
   8:     public static iwebhostbuilder createwebhostbuilder(string[] args) =>
   9:        webhost.createdefaultbuilder(args)
  10:           .usestartup<startup>();
  11:  }

v3.0模板中提供的createhostbuilder()方法看起来非常类似于v2.x中的createwebhostbuilder()。

其主要区别在于对webhost.createdefaultbuilder()由host.createdefaultbuilder()替换。使用createdefaultbuilder()辅助方法可以非常轻松地从v2.x切换到v3.0。

另一个区别是关于configurewebhostdefaults()的调用。由于新的主机构建器是通用主机构建器,因此我们必须让它知道我们打算为web主机配置默认设置。这些默认配置我们可以在configurewebhostdefaults()方法中实现

createdefaultbuilder

该方法microsoft.extensions.hosting.host中,它是一个静态类,里面有两个方法,一个有参的createdefaultbuilder(string[] args),一个是无参的。

无参方法源码如下,

   1:  public static ihostbuilder createdefaultbuilder() =>
   2:              createdefaultbuilder(args: null);

可以看到该方法实际上是设置了默认值。

ihostbuilder createdefaultbuilder(string[] args)方法主要有以下功能:

创建hostbuilder对象

   1:  var builder = new hostbuilder();

指定host要使用的内容根目录

   1:  builder.usecontentroot(directory.getcurrentdirectory());

配置初始化(环境变量、appsettings.json、user secrets)

   1:  builder.configurehostconfiguration(config =>
   2:  {
   3:      config.addenvironmentvariables(prefix: "dotnet_");
   4:      if (args != null)
   5:      {
   6:          config.addcommandline(args);
   7:      }
   8:  });
   9:   
  10:  builder.configureappconfiguration((hostingcontext, config) =>
  11:  {
  12:      var env = hostingcontext.hostingenvironment;
  13:   
  14:      config.addjsonfile("appsettings.json", optional: true, reloadonchange: true)
  15:            .addjsonfile($"appsettings.{env.environmentname}.json", optional: true, reloadonchange: true);
  16:   
  17:      if (env.isdevelopment() && !string.isnullorempty(env.applicationname))
  18:      {
  19:          var appassembly = assembly.load(new assemblyname(env.applicationname));
  20:          if (appassembly != null)
  21:          {
  22:              config.addusersecrets(appassembly, optional: true);
  23:          }
  24:      }
  25:   
  26:      config.addenvironmentvariables();
  27:   
  28:      if (args != null)
  29:      {
  30:          config.addcommandline(args);
  31:      }
  32:  })

日志

   1:  .configurelogging((hostingcontext, logging) =>
   2:  {
   3:      logging.addconfiguration(hostingcontext.configuration.getsection("logging"));
   4:      logging.addconsole();
   5:      logging.adddebug();
   6:      logging.addeventsourcelogger();
   7:  })

在开发环境模式下启用作用域验证

   1:  .usedefaultserviceprovider((context, options) =>
   2:  {
   3:      var isdevelopment = context.hostingenvironment.isdevelopment();
   4:      options.validatescopes = isdevelopment;
   5:      options.validateonbuild = isdevelopment;
   6:  });

build

build()方法是microsoft.extensions.hosting中,并且该方法只会执行一次,当然这种一次只是在同一个实例里面

   1:  public ihost build()
   2:  {
   3:      if (_hostbuilt)
   4:      {
   5:          throw new invalidoperationexception("build can only be called once.");
   6:      }
   7:      _hostbuilt = true;
   8:   
   9:      buildhostconfiguration();
  10:      createhostingenvironment();
  11:      createhostbuildercontext();
  12:      buildappconfiguration();
  13:      createserviceprovider();
  14:   
  15:      return _appservices.getrequiredservice<ihost>();
  16:  }

该方法主要是包括以下功能:

创建hostingenvironment

创建hostbuildercontext

配置初始化及格式标准化

di(创建ihostenvironment、ihostapplicationlifetime、ihostlifetime、ihost)

run

run方法运行应用程序并阻止调用线程,直到主机关闭

   1:  public static void run(this ihost host)
   2:  {
   3:      host.runasync().getawaiter().getresult();
   4:  }

以下是runasync的源码,此处可以通过设置cancellationtoken的值,使应用程序自动关闭

   1:  public static async task runasync(this ihost host, cancellationtoken token = default)
   2:  {
   3:      try
   4:      {
   5:          await host.startasync(token);
   6:   
   7:          await host.waitforshutdownasync(token);
   8:      }
   9:      finally
  10:      {
  11:  #if dispose_async
  12:          if (host is iasyncdisposable asyncdisposable)
  13:          {
  14:              await asyncdisposable.disposeasync();
  15:          }
  16:          else
  17:  #endif
  18:          {
  19:              host.dispose();
  20:          }
  21:   
  22:      }
  23:  }