.NET Core 3.0之深入源码理解Startup的注册及运行

时间:2022-06-26
本文章向大家介绍.NET Core 3.0之深入源码理解Startup的注册及运行,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

写在前面

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

Startup讨论

Starup所承担的角色

Startup作为一个概念是ASP.NET Core程序中所必须的,Startup类本身可以使用多种修饰符(public、protect,private、internal),作为ASP.NET Core应用程序的入口,它包含与应用程序相关配置的功能或者说是接口。

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

当然如果不想写Startup,可以在Program类中配置服务和请求处理管道,请参见评论区5楼,非常感谢Emrys耐心而又全面的指正

以下是基于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实例。

ConfigureServices和Configure

当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初始化完成。