深入探究ASP.NET Core Startup初始化问题
通过FindMethod要领我们可以获得几个结论,起首ConfigureServices要领的名称可所以包括情形变量的名称好比(ConfigureDevelopmentServices),其次要领可觉得共有的静态或非静态要领。FindMethod要领是真正执行查找的逻辑地址,假如找到相干要领例返回MethodInfo。FindMethod查找的要领名称是通过methodName参数转达进来的,我们标注的注释代码都是直接写死了ConfigureServices要领,只是为了便于声名领略,但着实FindMethod是通用要领,接下来我们要讲授的内容还会涉及到这个要领,到时辰关于这个代码的逻辑我们就不会在举办声名白,由于是统一个要领,但愿各人能留意到这一点。 internal class ConfigureServicesBuilder { //结构函数转达的configureServices的MethodInfo public ConfigureServicesBuilder(MethodInfo configureServices) { MethodInfo = configureServices; } public MethodInfo MethodInfo { get; } public Func<Func<IServiceCollection, IServiceProvider>, Func<IServiceCollection, IServiceProvider>> StartupServiceFilters { get; set; } = f => f; //Build委托 public Func<IServiceCollection, IServiceProvider> Build(object instance) => services => Invoke(instance, services); private IServiceProvider Invoke(object instance, IServiceCollection services) { //执行StartupServiceFilters委托参数为Func<IServiceCollection, IServiceProvider>范例的委托要领即Startup //返回了Func<IServiceCollection, IServiceProvider>委托,执行这个委托需转达services即IServiceCollections实例返回IServiceProvider范例 return StartupServiceFilters(Startup)(services); IServiceProvider Startup(IServiceCollection serviceCollection) => InvokeCore(instance, serviceCollection); } private IServiceProvider InvokeCore(object instance, IServiceCollection services) { if (MethodInfo == null) { return null; } // 假如ConfigureServices要领包括多个参数或要领参数范例不是IServiceCollection范例则直接抛出非常 // 也就是说ConfigureServices只能包括一个参数且范例为IServiceCollection var parameters = MethodInfo.GetParameters(); if (parameters.Length > 1 || parameters.Any(p => p.ParameterType != typeof(IServiceCollection))) { throw new InvalidOperationException("The ConfigureServices method must either be parameterless or take only one parameter of type IServiceCollection."); } //找到ConfigureServices要领的参数,并将services即IServiceCollection的实例转达给这个参数 var arguments = new object[MethodInfo.GetParameters().Length]; if (parameters.Length > 0) { arguments[0] = services; } // 执行返回IServiceProvider实例 return MethodInfo.InvokeWithoutWrappingExceptions(instance, arguments) as IServiceProvider; } } (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |