深入探究ASP.NET Core Startup初始化问题
internal static ConfigureServicesBuilder FindConfigureServicesDelegate(Type startupType, string environmentName) { //根据startupType和根据environmentName构建的Configure{0}Services字符串先去查找返回类型为IServiceProvider的方法 //找不到在查找返回值为void类型的方法 var servicesMethod = FindMethod(startupType, "Configure{0}Services", environmentName, typeof(IServiceProvider), required: false) ?? FindMethod(startupType, "Configure{0}Services", environmentName, typeof(void), required: false); //根据查找的到的MethodInfo去构建ConfigureServicesBuilder实例 return new ConfigureServicesBuilder(servicesMethod); } 通过这里的源码我们可以看到在startupType类型里去查找名字为environmentName构建的Configure{0}Services的方法信息,然后根据查找的方法信息即MethodInfo对象去构建ConfigureServicesBuilder实例。接下里我们就来查询FindMethod方法的实现 private static MethodInfo FindMethod(Type startupType, string methodName, string environmentName, Type returnType = null, bool required = true) { //包含环境变量的ConfigureServices方法名称比如(ConfigureDevelopmentServices) var methodNameWithEnv = string.Format(CultureInfo.InvariantCulture, methodName, environmentName); //名为ConfigureServices的方法 var methodNameWithNoEnv = string.Format(CultureInfo.InvariantCulture, methodName, ""); //方法是共有的静态的或非静态的方法 var methods = startupType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); //查找包含环境变量的ConfigureServices方法名称 var selectedMethods = methods.Where(method => method.Name.Equals(methodNameWithEnv, StringComparison.OrdinalIgnoreCase)).ToList(); if (selectedMethods.Count > 1) { //找打多个满足规则的方法直接抛出异常 throw new InvalidOperationException(string.Format("Having multiple overloads of method '{0}' is not supported.", methodNameWithEnv)); } //如果不存在包含环境变量的ConfigureServices的方法比如(ConfigureDevelopmentServices),则直接查找方法名为ConfigureServices的方法 if (selectedMethods.Count == 0) { selectedMethods = methods.Where(method => method.Name.Equals(methodNameWithNoEnv, StringComparison.OrdinalIgnoreCase)).ToList(); //如果存在多个则同样抛出异常 if (selectedMethods.Count > 1) { throw new InvalidOperationException(string.Format("Having multiple overloads of method '{0}' is not supported.", methodNameWithNoEnv)); } } var methodInfo = selectedMethods.FirstOrDefault(); //如果没找到满足规则的方法,并且满足required参数,则抛出未找到方法的异常 if (methodInfo == null) { if (required) { throw new InvalidOperationException(string.Format("A public method named '{0}' or '{1}' could not be found in the '{2}' type.", methodNameWithEnv, methodNameWithNoEnv, startupType.FullName)); } return null; } //如果找到了名称一致的方法,但是返回类型和预期的不一致,也抛出异常 if (returnType != null && methodInfo.ReturnType != returnType) { if (required) { throw new InvalidOperationException(string.Format("The '{0}' method in the type '{1}' must have a return type of '{2}'.", methodInfo.Name, startupType.FullName, returnType.Name)); } return null; } return methodInfo; } (编辑:西安站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |