设为首页 - 加入收藏 PHP编程网 - PHP站长网 (http://www.52php.cn)- 电商,百科,编程,业界,移动互联,5G,云计算,站长网!
热搜: 娱乐 服务 百度 表达
当前位置: 首页 > 编程 > 正文

深入探究ASP.NET Core Startup初始化问题(9)

发布时间:2020-12-10 22:35 所属栏目:[编程] 来源:网络整理
导读:如果你在ASP.NET Core 3.1中使用过Autofac那么你对ConfigureContainer方法一定不陌生,它和ConfigureServices、Configure方法一样的神奇,在几乎没有任何约束的情况下我们只需要定义ConfigureContainer方法并为方法

如果你在ASP.NET Core 3.1中使用过Autofac那么你对ConfigureContainer方法一定不陌生,它和ConfigureServices、Configure方法一样的神奇,在几乎没有任何约束的情况下我们只需要定义ConfigureContainer方法并为方法传递一个ContainerBuilder参数,那么这个方法就能顺利的被调用了。这一切究竟是如何实现的呢,接下来我们继续探究源码,找到了如下的逻辑
[点击查看源码👈]

//根据规则查找最终返回ConfigureContainerBuilder实例 var configureContainerBuilder = StartupLoader.FindConfigureContainerDelegate(startupType, context.HostingEnvironment.EnvironmentName); if (configureContainerBuilder.MethodInfo != null) { //获取容器类型比如如果是autofac则类型为ContainerBuilder var containerType = configureContainerBuilder.GetContainerType(); // 存储configureContainerBuilder实例 _builder.Properties[typeof(ConfigureContainerBuilder)] = configureContainerBuilder; //构建一个Action<HostBuilderContext,containerType>类型的委托 var actionType = typeof(Action<,>).MakeGenericType(typeof(HostBuilderContext), containerType); // 获取此类型的私有ConfigureContainer方法,然后声明该方法的泛型为容器类型,然后创建这个方法的委托 var configureCallback = GetType().GetMethod(nameof(ConfigureContainer), BindingFlags.NonPublic | BindingFlags.Instance) .MakeGenericMethod(containerType) .CreateDelegate(actionType, this); // 等同于执行_builder.ConfigureContainer<T>(ConfigureContainer),其中T为容器类型。 //C onfigureContainer表示一个委托,即我们在Startup中定义的ConfigureContainer委托 typeof(IHostBuilder).GetMethods().First(m => m.Name == nameof(IHostBuilder.ConfigureContainer)) .MakeGenericMethod(containerType) .InvokeWithoutWrappingExceptions(_builder, new object[] { configureCallback }); }

继续使用老配方,我们查看StartupLoader的FindConfigureContainerDelegate方法实现
[点击查看源码👈]

【免责声明】本站内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

推荐文章
热点阅读