欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【春华秋实】深入源码理解.NET Core中Startup的注册及运行

程序员文章站 2022-07-07 08:22:16
写在前面 开发.NET Core应用,直接映入眼帘的就是Startup类和Program类,它们是.NET Core应用程序的起点。通过使用Startup,可以配置化处理所有向应用程序所做的请求的管道,同时也可以减少.NET应用程序对单一服务器的依赖性,使我们在更大程度上专注于面向多服务器为中心的开 ......
 

写在前面

开发.net core应用,直接映入眼帘的就是startup类和program类,它们是.net core应用程序的起点。通过使用startup,可以配置化处理所有向应用程序所做的请求的管道,同时也可以减少.net应用程序对单一服务器的依赖性,使我们在更大程度上专注于面向多服务器为中心的开发模式。

目录:

  • startup讨论
    • starup所承担的角色
    • startup编写规范
    • configureservices
    • configure
    • 扩展startup方法
  • 深入源码查看startup是如何注册和执行的
    • usestartup源码
    • 创建startup实例
    • configureservices和configure

startup讨论

starup所承担的角色

startup类是asp.net core程序中所必须的,可以使用多种修饰符(public、protect,private、internal),作为asp.net core应用程序的入口,它包含与应用程序相关配置的功能或者说是接口。

虽然在程序里我们使用的类名就是startup,但是需要注意的是,startup是一个抽象概念,你完全可以名称成其他的,比如myappstartup或者其他的什么名称,只要你在program类中启动你所定义的启动类即可。

以下是基于asp.net core preview 3模板中提供的写法:

   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:  }

不管你命名成什么,只要将webbuilder.usestartup<>()中的泛型类配置成你定义的入口类即可;

startup编写规范

下面是asp.net core 3.0 preview 3模板中startup的写法:

   1:  // this method gets called by the runtime. use this method to configure the http request pipeline.
   2:  public void configure(iapplicationbuilder app, iwebhostenvironment env)
   3:  {
   4:      if (env.isdevelopment())
   5:      {
   6:          app.usedeveloperexceptionpage();
   7:      }
   8:      else
   9:      {
  10:          // the default hsts value is 30 days. you may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  11:          app.usehsts();
  12:      }
  13:   
  14:      app.usehttpsredirection();
  15:   
  16:      app.userouting(routes =>
  17:      {
  18:          routes.mapcontrollers();
  19:      });
  20:   
  21:      app.useauthorization();
  22:  }

通过以上代码可以知道,startup类中一般包括

  • 构造函数:通过我们以前的开发经验,我们可以知道,该构造方法可以包括多个对象
    • iconfiguration:表示一组键/值应用程序配置属性。
    • iapplicationbuilder:是一个包含与当前环境相关的属性和方法的接口。它用于获取应用程序中的环境变量。
    • ihostingenvironment:是一个包含与运行应用程序的web宿主环境相关信息的接口。使用这个接口方法,我们可以改变应用程序的行为。
    • iloggerfactory:是为asp.net core中的日志记录系统提供配置的接口。它还创建日志系统的实例。
  • configureservices
  • configure

startup在创建服务时,会执行依赖项注册服务,以便在应用程序的其它地方使用这些依赖项。configureservices 用于注册服务,configure 方法允许我们向http管道添加中间件和服务。这就是configureservices先于configure 之前调用的原因。

 

configureservices

该方法时可选的,非强制约束,它主要用于对依赖注入或applicationservices在整个应用中的支持,该方法必须是public的,其典型模式是调用所有 add{service} 方法,主要场景包括实体框架、认证和 mvc 注册服务:

   1:  services.adddbcontext<applicationdbcontext>(options =>options.usesqlserver(configuration.getconnectionstring("defaultconnection")));
   2:  services.adddefaultidentity<identityuser>().adddefaultui(uiframework.bootstrap4).addentityframeworkstores<applicationdbcontext>();
   3:  services.addmvc().setcompatibilityversion(compatibilityversion.version_2_2);
   4:  // add application services.此处主要是注册ioc服务
   5:  services.addtransient<iemailsender, authmessagesender>();
   6:  services.addtransient<ismssender, authmessagesender>();

configure

该方法主要用于定义应用程序对每个http请求的响应方式,即我们可以控制asp.net管道,还可用于在http管道中配置中间件。请求管道中的每个中间件组件负责调用管道中的下一个组件,或在适当情况下使链发生短路。 如果中间件链中未发生短路,则每个中间件都有第二次机会在将请求发送到客户端前处理该请求。

该方法接受iapplicationbuilder作为参数,同时还可以接收其他一些可选参数,如ihostingenvironment和iloggerfactory。

一般而言,只要将服务注册到configureservices方法中时,都可以在该方法中使用。

   1:  app.usedeveloperexceptionpage();   
   2:  app.usehsts();   
   3:  app.usehttpsredirection();   
   4:  app.userouting(routes =>   
   5:  {   
   6:      routes.mapcontrollers();   
   7:  });   
   8:  app.useauthorization();

扩展startup方法

使用istartupfilter来对startup功能进行扩展,在应用的configure中间件管道的开头或末尾使用istartupfilter来配置中间件。istartupfilter有助于确保当库在应用请求处理管道的开端或末尾添加中间件的前后运行中间件。

以下是istartupfilter的源代码,通过源代码我们可以知道,该接口有一个action<iapplicationbuilder>类型,并命名为configure的方法。由于传入参数类型和返回类型一样,这就保证了扩展的传递性及顺序性,具体的演示代码,可以参数msdn

   1:  using system;
   2:  using microsoft.aspnetcore.builder;
   3:   
   4:  namespace microsoft.aspnetcore.hosting
   5:  {
   6:      public interface istartupfilter
   7:      {
   8:          action<iapplicationbuilder> configure(action<iapplicationbuilder> next);
   9:      }
  10:  }

startup是如何注册和执行的

此段文字,只是我想深入了解其内部机制而写的,如果本身也不了解,其实是不影响我们正常编写.net core应用的。

usestartup源码

asp.net core通过调用iwebhostbuilder.usestartup方法,传入startup类型,注意开篇就已经说过startup是一个抽象概念,我们看下源代码:

   1:  /// <summary>
   2:   /// specify the startup type to be used by the web host.
   3:   /// </summary>
   4:   /// <param name="hostbuilder">the <see cref="iwebhostbuilder"/> to configure.</param>
   5:   /// <param name="startuptype">the <see cref="type"/> to be used.</param>
   6:   /// <returns>the <see cref="iwebhostbuilder"/>.</returns>
   7:   public static iwebhostbuilder usestartup(this iwebhostbuilder hostbuilder, type startuptype)
   8:   {
   9:       var startupassemblyname = startuptype.gettypeinfo().assembly.getname().name;
  10:   
  11:      hostbuilder.usesetting(webhostdefaults.applicationkey, startupassemblyname);
  12:   
  13:      // light up the genericwebhostbuilder implementation
  14:      if (hostbuilder is isupportsstartup supportsstartup)
  15:      {
  16:          return supportsstartup.usestartup(startuptype);
  17:      }
  18:   
  19:      return hostbuilder
  20:          .configureservices(services =>
  21:          {
  22:              if (typeof(istartup).gettypeinfo().isassignablefrom(startuptype.gettypeinfo()))
  23:              {
  24:                  services.addsingleton(typeof(istartup), startuptype);
  25:              }
  26:              else
  27:              {
  28:                  services.addsingleton(typeof(istartup), sp =>
  29:                  {
  30:                      var hostingenvironment = sp.getrequiredservice<ihostenvironment>();
  31:                      return new conventionbasedstartup(startuploader.loadmethods(sp, startuptype, hostingenvironment.environmentname));
  32:                  });
  33:              }
  34:          });
  35:  }
  36:   
  37:  /// <summary>
  38:  /// specify the startup type to be used by the web host.
  39:  /// </summary>
  40:  /// <param name="hostbuilder">the <see cref="iwebhostbuilder"/> to configure.</param>
  41:  /// <typeparam name ="tstartup">the type containing the startup methods for the application.</typeparam>
  42:  /// <returns>the <see cref="iwebhostbuilder"/>.</returns>
  43:  public static iwebhostbuilder usestartup<tstartup>(this iwebhostbuilder hostbuilder) where tstartup : class
  44:  {
  45:      return hostbuilder.usestartup(typeof(tstartup));
  46:  }

创建startup实例

   1:  /// <summary>
   2:  /// adds a delegate for configuring additional services for the host or web application. this may be called
   3:  /// multiple times.
   4:  /// </summary>
   5:  /// <param name="configureservices">a delegate for configuring the <see cref="iservicecollection"/>.</param>
   6:  /// <returns>the <see cref="iwebhostbuilder"/>.</returns>
   7:  public iwebhostbuilder configureservices(action<iservicecollection> configureservices)
   8:  {
   9:      if (configureservices == null)
  10:      {
  11:          throw new argumentnullexception(nameof(configureservices));
  12:      }
  13:   
  14:      return configureservices((_, services) => configureservices(services));
  15:  }
  16:   
  17:  /// <summary>
  18:  /// adds a delegate for configuring additional services for the host or web application. this may be called
  19:  /// multiple times.
  20:  /// </summary>
  21:  /// <param name="configureservices">a delegate for configuring the <see cref="iservicecollection"/>.</param>
  22:  /// <returns>the <see cref="iwebhostbuilder"/>.</returns>
  23:  public iwebhostbuilder configureservices(action<webhostbuildercontext, iservicecollection> configureservices)
  24:  {
  25:      _configureservices += configureservices;
  26:      return this;
  27:  }

关于configureservices的定义及注册方式,是在iwebhostbuilder.configureservices实现的,同时可以注意一下25行代码,向大家说明了多次注册startup的configureservices方法时,会合并起来的根源。此处抽象委托用的也非常多。

该类里面还有build方法,我就不贴出代码了,只需要知道,主进程在此处开始了。接下来一个比较重要的方法,是buildcommonservices,它向当前servicecollection中添加一些公共框架级服务,以下是部分代码,具体代码请查看webhostbuilder

   1:  try
   2:  {
   3:      var startuptype = startuploader.findstartuptype(_options.startupassembly, _hostingenvironment.environmentname);
   4:   
   5:      if (typeof(istartup).gettypeinfo().isassignablefrom(startuptype.gettypeinfo()))
   6:      {
   7:          services.addsingleton(typeof(istartup), startuptype);
   8:      }
   9:      else
  10:      {
  11:          services.addsingleton(typeof(istartup), sp =>
  12:          {
  13:              var hostingenvironment = sp.getrequiredservice<ihostenvironment>();
  14:              var methods = startuploader.loadmethods(sp, startuptype, hostingenvironment.environmentname);
  15:              return new conventionbasedstartup(methods);
  16:          });
  17:      }
  18:  }
  19:  catch (exception ex)
  20:  {
  21:      var capture = exceptiondispatchinfo.capture(ex);
  22:      services.addsingleton<istartup>(_ =>
  23:      {
  24:          capture.throw();
  25:          return null;
  26:      });
  27:  }
由此可见,如果我们的startup类直接实现istartup,它可以并且将直接注册为istartup的实现类型。只不过asp.net core模板代码并没有实现istartup,它更多的是一种约定,并通过di调用委托,依此调用startup内的构造函数还有另外两个方法。
同时上述代码还展示了如何创建startup类型,就是用到了静态方法startuploader.loadmethods类生成startupmethods实例。

configureservicesconfigure

当webhost初始化时,框架会去查找相应的方法,这里,我们主要查看源代码,其中的核心方法是startuploader.findmethods
   1:  private static methodinfo findmethod(type startuptype, string methodname, string environmentname, type returntype = null, bool required = true)
   2:  {
   3:      var methodnamewithenv = string.format(cultureinfo.invariantculture, methodname, environmentname);
   4:      var methodnamewithnoenv = string.format(cultureinfo.invariantculture, methodname, "");
   5:   
   6:      var methods = startuptype.getmethods(bindingflags.public | bindingflags.instance | bindingflags.static);
   7:      var selectedmethods = methods.where(method => method.name.equals(methodnamewithenv, stringcomparison.ordinalignorecase)).tolist();
   8:      if (selectedmethods.count > 1)
   9:      {
  10:          throw new invalidoperationexception(string.format("having multiple overloads of method '{0}' is not supported.", methodnamewithenv));
  11:      }
  12:      if (selectedmethods.count == 0)
  13:      {
  14:          selectedmethods = methods.where(method => method.name.equals(methodnamewithnoenv, stringcomparison.ordinalignorecase)).tolist();
  15:          if (selectedmethods.count > 1)
  16:          {
  17:              throw new invalidoperationexception(string.format("having multiple overloads of method '{0}' is not supported.", methodnamewithnoenv));
  18:          }
  19:      }
  20:   
  21:      var methodinfo = selectedmethods.firstordefault();
  22:      if (methodinfo == null)
  23:      {
  24:          if (required)
  25:          {
  26:              throw new invalidoperationexception(string.format("a public method named '{0}' or '{1}' could not be found in the '{2}' type.",
  27:                  methodnamewithenv,
  28:                  methodnamewithnoenv,
  29:                  startuptype.fullname));
  30:   
  31:          }
  32:          return null;
  33:      }
  34:      if (returntype != null && methodinfo.returntype != returntype)
  35:      {
  36:          if (required)
  37:          {
  38:              throw new invalidoperationexception(string.format("the '{0}' method in the type '{1}' must have a return type of '{2}'.",
  39:                  methodinfo.name,
  40:                  startuptype.fullname,
  41:                  returntype.name));
  42:          }
  43:          return null;
  44:      }
  45:      return methodinfo;
  46:  }
它查找的第一个委托是configuredelegate,该委托将用于构建应用程序的中间件管道。findmethod完成了大部分工作,具体的代码请查看startuploader。此方法根据传递给它的methodname参数在startup类中查找响应的方法。
我们知道,startup的定义更多的是约定,所以会去查找configure和configureservices。当然,通过源代码我还知道,除了提供标准的“configure”方法之外,我们还可以通过环境配置找到响应的configure和configureservices。根本来说,我们最终查找到的是configurecontainerdelegate。
接下来,一个比较重要的方法是loadmethods
   1:  public static startupmethods loadmethods(iserviceprovider hostingserviceprovider, type startuptype, string environmentname)
   2:  {
   3:      var configuremethod = findconfiguredelegate(startuptype, environmentname);
   4:   
   5:      var servicesmethod = findconfigureservicesdelegate(startuptype, environmentname);
   6:      var configurecontainermethod = findconfigurecontainerdelegate(startuptype, environmentname);
   7:   
   8:      object instance = null;
   9:      if (!configuremethod.methodinfo.isstatic || (servicesmethod != null && !servicesmethod.methodinfo.isstatic))
  10:      {
  11:          instance = activatorutilities.getserviceorcreateinstance(hostingserviceprovider, startuptype);
  12:      }
  13:   
  14:      // the type of the tcontainerbuilder. if there is no configurecontainer method we can just use object as it's not
  15:      // going to be used for anything.
  16:      var type = configurecontainermethod.methodinfo != null ? configurecontainermethod.getcontainertype() : typeof(object);
  17:   
  18:      var builder = (configureservicesdelegatebuilder) activator.createinstance(
  19:          typeof(configureservicesdelegatebuilder<>).makegenerictype(type),
  20:          hostingserviceprovider,
  21:          servicesmethod,
  22:          configurecontainermethod,
  23:          instance);
  24:   
  25:      return new startupmethods(instance, configuremethod.build(instance), builder.build());
  26:  }
 
该方法通过查找对应的方法,由于startup并未在di中注册,所以会调用getserviceorcreateinstance创建一个startup实例,此时构造函数也在此得到解析。
通过一系列的调用,最终到达了configureservicesbuilder.invoke里面。invoke方法使用反射来获取和检查在startup类上定义的configureservices方法所需的参数。
   1:  private iserviceprovider invokecore(object instance, iservicecollection services)
   2:  {
   3:      if (methodinfo == null)
   4:      {
   5:          return null;
   6:      }
   7:   
   8:      // only support iservicecollection parameters
   9:      var parameters = methodinfo.getparameters();
  10:      if (parameters.length > 1 ||
  11:          parameters.any(p => p.parametertype != typeof(iservicecollection)))
  12:      {
  13:          throw new invalidoperationexception("the configureservices method must either be parameterless or take only one parameter of type iservicecollection.");
  14:      }
  15:   
  16:      var arguments = new object[methodinfo.getparameters().length];
  17:   
  18:      if (parameters.length > 0)
  19:      {
  20:          arguments[0] = services;
  21:      }
  22:   
  23:      return methodinfo.invoke(instance, arguments) as iserviceprovider;
  24:  }

最后我们来看一下configurebuilder类,它需要一个action<iapplicationbuilder>委托变量,其中包含每个istartupfilter的一组包装的configure方法,最后一个是startup.configure方法的委托。此时,所调用的配置链首先命中的是autorequestservicesstartupfilter.configure方法。并将该委托链作为下一个操作,之后会调用conventionbasedstartup.configure方法。这将在其本地startupmethods对象上调用configuredelegate。

   1:  private void invoke(object instance, iapplicationbuilder builder)
   2:  {
   3:      // create a scope for configure, this allows creating scoped dependencies
   4:      // without the hassle of manually creating a scope.
   5:      using (var scope = builder.applicationservices.createscope())
   6:      {
   7:          var serviceprovider = scope.serviceprovider;
   8:          var parameterinfos = methodinfo.getparameters();
   9:          var parameters = new object[parameterinfos.length];
  10:          for (var index = 0; index < parameterinfos.length; index++)
  11:          {
  12:              var parameterinfo = parameterinfos[index];
  13:              if (parameterinfo.parametertype == typeof(iapplicationbuilder))
  14:              {
  15:                  parameters[index] = builder;
  16:              }
  17:              else
  18:              {
  19:                  try
  20:                  {
  21:                      parameters[index] = serviceprovider.getrequiredservice(parameterinfo.parametertype);
  22:                  }
  23:                  catch (exception ex)
  24:                  {
  25:                      throw new exception(string.format(
  26:                          "could not resolve a service of type '{0}' for the parameter '{1}' of method '{2}' on type '{3}'.",
  27:                          parameterinfo.parametertype.fullname,
  28:                          parameterinfo.name,
  29:                          methodinfo.name,
  30:                          methodinfo.declaringtype.fullname), ex);
  31:                  }
  32:              }
  33:          }
  34:          methodinfo.invoke(instance, parameters);
  35:      }
  36:  }

startup.configure方法会调用serviceprovider所解析的相应的参数,该方法还可以使用iapplicationbuilder将中间件添加到应用程序管道中。最终的requestdelegate是从iapplicationbuilder构建并返回的,至此webhost初始化完成。