Asp.net core 中的Startup类是啥?

前言碎语

上一篇中, 我写了一个小的实例来运行简单的web 服务. 用心的看官肯定发现了, 在我的项目中有一个Startup类, 此类并没有继承任何接口, 只是实现了一个Configure方法, 这个Configure方法则是主要的逻辑所在了. 那么, 这个Startup类是如何被Web 服务调用的, 怎能在没有实现任何接口的情况下被调用呢?

深入调研

dotnet core 自诞生以来便为dotnet 社区带来了跨平台和开源, 两个当今互联网技术不可或缺的属性. 要说这几年来, 由于dotnet跨平台的不利, dotnet社区已经日渐式微. 2016年发布的dotnet core可谓直指要害, 微软也希望借开源社区之力把dotnet 平台推向一个新的高峰.
既然是开源, 我们就有机会获取到更多有用的信息, 帮助我们更加深刻的理解dotnet 平台. 带着上面的问题, 我们来看看源码. 源码地址, 有兴趣的童鞋自行查阅.
打开源码后很容易发现, 原来在Microsoft.AspNetCore.Hosting有一个StartupBase基类, 并且实现了IStartup接口. 感觉直接继承基类, 实现一个Startup类也是可以的. 童鞋们敬请尝试.

再来看下demo中的代码:

    var host = new WebHostBuilder()
        .UseKestrel()
        .UseStartup<Startup>()
        .Build();

    host.Run();

涉及到Startup类的方法是UseStartup这个函数. 打开源码可以透过重载找到如下实现:

    public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, Type startupType)
    {
        var startupAssemblyName = startupType.GetTypeInfo().Assembly.GetName().Name;

        return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey, startupAssemblyName)
                          .ConfigureServices(services =>
                          {
                              if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
                              {
                                  services.AddSingleton(typeof(IStartup), startupType);
                              }
                              else
                              {
                                  services.AddSingleton(typeof(IStartup), sp =>
                                  {
                                      var hostingEnvironment = sp.GetRequiredService<IHostingEnvironment>();
                                      return new ConventionBasedStartup(StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName));
                                  });
                              }
                          });
    }

果不其然, 源码中也对是否继承IStartup接口进行了检查, 并分别有两个不同的逻辑分支. 我们暂且看没有实现接口的一支.

直观的看代码, 意图很明显, 要把Startup类中的方法作为具体逻辑, 加入到一个单例的服务中. 具体的实现逻辑应该在这一句:

return new ConventionBasedStartup(StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName));

看下ConventionBasedStartup类的定义:

public class ConventionBasedStartup : IStartup

看到这样的接口继承, 我突然感慨到, 自己是多么的睿智. Hosting类库自动将我们的非接口继承的Startup类转换成继承接口的形式, 不可谓不蛋疼.

洞察天机

接着我找到了主要的代码逻辑, 先来看一下是如何找到Startup类中的Configure方法的:

    private static ConfigureBuilder FindConfigureDelegate(Type startupType, string environmentName)
    {
        var configureMethod = FindMethod(startupType, "Configure{0}", environmentName, typeof(void), required: true);
        return new ConfigureBuilder(configureMethod);
    }

就是这样的一段代码, 没错, 竟然是字符串匹配, 换句话说, 你必须要在Startup中实现Configure方法, 不然...

接着看这段:

    public static StartupMethods LoadMethods(IServiceProvider hostingServiceProvider, Type startupType, string environmentName)
    {
        var configureMethod = FindConfigureDelegate(startupType, environmentName);
        var servicesMethod = FindConfigureServicesDelegate(startupType, environmentName);
        var configureContainerMethod = FindConfigureContainerDelegate(startupType, environmentName);

        object instance = null;
        if (!configureMethod.MethodInfo.IsStatic || (servicesMethod != null && !servicesMethod.MethodInfo.IsStatic))
        {
            instance = ActivatorUtilities.GetServiceOrCreateInstance(hostingServiceProvider, startupType);
        }

        var configureServicesCallback = servicesMethod.Build(instance);
        var configureContainerCallback = configureContainerMethod.Build(instance);

        Func<IServiceCollection, IServiceProvider> configureServices = services =>
        {
            // Call ConfigureServices, if that returned an IServiceProvider, we're done
            IServiceProvider applicationServiceProvider = configureServicesCallback.Invoke(services);

            if (applicationServiceProvider != null)
            {
                return applicationServiceProvider;
            }

            // If there's a ConfigureContainer method
            if (configureContainerMethod.MethodInfo != null)
            {
                // We have a ConfigureContainer method, get the IServiceProviderFactory<TContainerBuilder>
                var serviceProviderFactoryType = typeof(IServiceProviderFactory<>).MakeGenericType(configureContainerMethod.GetContainerType());
                var serviceProviderFactory = hostingServiceProvider.GetRequiredService(serviceProviderFactoryType);
                // var builder = serviceProviderFactory.CreateBuilder(services);
                var builder = serviceProviderFactoryType.GetMethod(nameof(DefaultServiceProviderFactory.CreateBuilder)).Invoke(serviceProviderFactory, new object[] { services });
                configureContainerCallback.Invoke(builder);
                // applicationServiceProvider = serviceProviderFactory.CreateServiceProvider(builder);
                applicationServiceProvider = (IServiceProvider)serviceProviderFactoryType.GetMethod(nameof(DefaultServiceProviderFactory.CreateServiceProvider)).Invoke(serviceProviderFactory, new object[] { builder });
            }
            else
            {
                // Get the default factory
                var serviceProviderFactory = hostingServiceProvider.GetRequiredService<IServiceProviderFactory<IServiceCollection>>();

                // Don't bother calling CreateBuilder since it just returns the default service collection
                applicationServiceProvider = serviceProviderFactory.CreateServiceProvider(services);
            }

            return applicationServiceProvider ?? services.BuildServiceProvider();
        };

        return new StartupMethods(configureMethod.Build(instance), configureServices);
    }

微软为了方便开发人员, 竟然大费周章用到反射处理一个Startup. 不禁感叹, 微软的攻城狮们, 你们是有多闲?

如果您觉得这篇文章对您有那么一丁点益处, 或者从某个角度触动到了您, 请给川酷一些鼓励, 打赏, 点赞, 关注, 哪怕评论区骂我两句, 鄙人都感激涕零.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容

  • 前言 这个标题也许并不适合这个系列, 因为距离上篇已经半个月有余, 是不是该改名为源码半月读? 为了不让懒癌再次发...
    春上川酷阅读 1,301评论 0 3
  • 开篇 之前写过Asp.net core 中的Startup类是啥?和dotnet core 打造干净的Web AP...
    春上川酷阅读 5,231评论 0 10
  • 一、设计模式的分类 总体来说设计模式分为三大类: 创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者...
    lichengjin阅读 881评论 0 8
  • 静谧里 一任退潮的倦意湮没 玻璃壁上斜晖脉脉 你如万象山河 我忘记时光 也忘记了一片叶子的纹络
    丁松青阅读 280评论 6 14
  • 玩着赚钱,需要什么技能和心态? 要想玩着赚钱,首要的一种心态就是玩,而不是一门心思地赚钱,如果我们能够好好玩,专业...
    晓丽姐阅读 436评论 3 0