開發.NET Core應用,直接映入眼簾的就是Startup類和Program類,它們是.NET Core應用程序的起點。經過使用Startup,能夠配置化處理全部嚮應用程序所作的請求的管道,同時也能夠減小.NET應用程序對單一服務器的依賴性,使咱們在更大程度上專一於面向多服務器爲中心的開發模式。html
目錄:ios
Startup做爲一個概念是ASP.NET Core程序中所必須的,Startup類自己可使用多種修飾符(public、protect,private、internal),做爲ASP.NET Core應用程序的入口,它包含與應用程序相關配置的功能或者說是接口。git
雖然在程序裏咱們使用的類名就是Startup,可是須要注意的是,Startup是一個抽象概念,你徹底能夠名稱成其餘的,好比MyAppStartup或者其餘的什麼名稱,只要你在Program類中啓動你所定義的啓動類便可。github
固然若是不想寫Startup,能夠在Program類中配置服務和請求處理管道,請參見評論區5樓,很是感謝Emrys耐心而又全面的指正。web
如下是基於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<>()中的泛型類配置成你定義的入口類便可;app
下面是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類中通常包括less
Startup在建立服務時,會執行依賴項註冊服務,以便在應用程序的其它地方使用這些依賴項。ConfigureServices 用於註冊服務,Configure 方法容許咱們向HTTP管道添加中間件和服務。這就是ConfigureServices先於Configure 以前調用的緣由。ide
該方法時可選的,非強制約束,它主要用於對依賴注入或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>();
該方法主要用於定義應用程序對每一個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();
使用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: }
此段文字,只是我想深刻了解其內部機制而寫的,若是自己也不瞭解,實際上是不影響咱們正常編寫.NET Core應用的。
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: }
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實例。
當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初始化完成。