博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.NET Core开发日志——Startup
阅读量:5284 次
发布时间:2019-06-14

本文共 11095 字,大约阅读时间需要 36 分钟。

原文:

一个典型的ASP.NET Core应用程序会包含Program与Startup两个文件。Program类中有应用程序的入口方法Main,其中的处理逻辑通常是创建一个WebHostBuilder,再生成WebHost,最后启动之。

而在创建WebHostBuilder时又会常常会指定一个Startup类型。

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>    WebHost.CreateDefaultBuilder(args)        .UseStartup
();

这个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
(); return new ConventionBasedStartup(StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName)); }); } });}

可以看出所指定的Startup类型会在DI容器中注册为单例形式,注册的处理过程被封装成Action

同时Startup类型可以有两种实现方式:

  • 自定义实现IStartup接口的类
  • 内部定义的ConventionBasedStartup类

实际使用的Startup类经常是这样的:

public class Startup{    public Startup(IConfiguration configuration)    {        Configuration = configuration;    }    public IConfiguration Configuration { get; }    public void ConfigureServices(IServiceCollection services)    {        ...    }    public void Configure(IApplicationBuilder app, IHostingEnvironment env)    {        ...    }}

所以明显不是第一种方式,那么其又是怎么与第二种方式关联起来的?

ConventionBasedStartup的构造方法中传入了StartupMethods类型的参数,它的LoadMethod方法里曝露了更多的信息。

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);    }    // The type of the TContainerBuilder. If there is no ConfigureContainer method we can just use object as it's not    // going to be used for anything.    var type = configureContainerMethod.MethodInfo != null ? configureContainerMethod.GetContainerType() : typeof(object);    var builder = (ConfigureServicesDelegateBuilder) Activator.CreateInstance(        typeof(ConfigureServicesDelegateBuilder<>).MakeGenericType(type),        hostingServiceProvider,        servicesMethod,        configureContainerMethod,        instance);    return new StartupMethods(instance, configureMethod.Build(instance), builder.Build());}

它的内部处理中会找寻三种方法,ConfigureServices, Configure与ConfigureContainer。

private static ConfigureBuilder FindConfigureDelegate(Type startupType, string environmentName){    var configureMethod = FindMethod(startupType, "Configure{0}", environmentName, typeof(void), required: true);    return new ConfigureBuilder(configureMethod);}private static ConfigureContainerBuilder FindConfigureContainerDelegate(Type startupType, string environmentName){    var configureMethod = FindMethod(startupType, "Configure{0}Container", environmentName, typeof(void), required: false);    return new ConfigureContainerBuilder(configureMethod);}private static ConfigureServicesBuilder FindConfigureServicesDelegate(Type startupType, string environmentName){    var servicesMethod = FindMethod(startupType, "Configure{0}Services", environmentName, typeof(IServiceProvider), required: false)        ?? FindMethod(startupType, "Configure{0}Services", environmentName, typeof(void), required: false);    return new ConfigureServicesBuilder(servicesMethod);}

ConfigureServices方法用于在容器中注册各种所需使用的服务接口类型,Configure方法中可以使用各种middleware(中间件),对HTTP请求pipeline(管道)进行配置。

这二者与IStartup接口的方法基本一致,而ConfigureContainer方法则是提供了一种引入第三方DI容器的功能。

public interface IStartup{    IServiceProvider ConfigureServices(IServiceCollection services);    void Configure(IApplicationBuilder app);}

使用第二种Startup类型的实现方式时,对于Configure方法的参数也可以更加灵活,不仅可以传入IApplicationBuilder类型,还可以有其它已注册过的任意接口类型。

ConfigureBuilder类的Build方法对额外参数的处理方法简单明了,是IApplicationBuilder类型的直接传入参数实例,不是的则从DI容器中获取实例:

public class ConfigureBuilder{    public Action
Build(object instance) => builder => Invoke(instance, builder); private void Invoke(object instance, IApplicationBuilder builder) { // Create a scope for Configure, this allows creating scoped dependencies // without the hassle of manually creating a scope. using (var scope = builder.ApplicationServices.CreateScope()) { var serviceProvider = scope.ServiceProvider; var parameterInfos = MethodInfo.GetParameters(); var parameters = new object[parameterInfos.Length]; for (var index = 0; index < parameterInfos.Length; index++) { var parameterInfo = parameterInfos[index]; if (parameterInfo.ParameterType == typeof(IApplicationBuilder)) { parameters[index] = builder; } else { try { parameters[index] = serviceProvider.GetRequiredService(parameterInfo.ParameterType); } ... } } MethodInfo.Invoke(instance, parameters); } }}

此外,在找寻各种方法的处理中可以看到环境变量的身影。所以用第二种方式可以依据不同的环境变量定义同类型但不同名称的方法,这样可以省去写不少if...else...的处理。

UseStartup方法中还只是申明了需要注册Startup类型,实际的调用是在WebHostBuilder类执行Build方法时发生的。

private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors){    ...    foreach (var configureServices in _configureServicesDelegates)    {        configureServices(_context, services);    }    return services;    }

至于Startup类型中方法的调用时机,则需跟踪到WebHost类中。

首先是它的Initialize方法会确保获得Startup类的实例,并调用ConfigureServices方法注册服务接口。

private void EnsureApplicationServices(){    if (_applicationServices == null)    {        EnsureStartup();        _applicationServices = _startup.ConfigureServices(_applicationServiceCollection);    }}private void EnsureStartup(){    if (_startup != null)    {        return;    }    _startup = _hostingServiceProvider.GetService
(); ...}

然后WebHost实例被启动时,它的BuildApplication方法会创建一个ApplicationBuilder实例,以其作为Configure方法参数,同时调用Configure方法,这时Configure方法中对那些middleware的处理方式(即Func<RequestDelegate, RequestDelegate>方法)会被加入到ApplicationBuilder之中。

private RequestDelegate BuildApplication(){    try    {        _applicationServicesException?.Throw();        EnsureServer();        var builderFactory = _applicationServices.GetRequiredService
(); var builder = builderFactory.CreateBuilder(Server.Features); builder.ApplicationServices = _applicationServices; var startupFilters = _applicationServices.GetService
>(); Action
configure = _startup.Configure; foreach (var filter in startupFilters.Reverse()) { configure = filter.Configure(configure); } configure(builder); return builder.Build(); } ...}

ApplicationBuilder的Build方法将这些处理逻辑嵌套起来,最底层的是返回404未找到的处理逻辑。

public RequestDelegate Build(){    RequestDelegate app = context =>    {        context.Response.StatusCode = 404;        return Task.CompletedTask;    };    foreach (var component in _components.Reverse())    {        app = component(app);    }    return app;}

BuildApplication方法返回已嵌套的RequestDelegate委托方法,并在之后生成的HostingApplication实例中,将其传入它的构造方法。

public virtual async Task StartAsync(CancellationToken cancellationToken = default){    HostingEventSource.Log.HostStart();    _logger = _applicationServices.GetRequiredService
>(); _logger.Starting(); var application = BuildApplication(); _applicationLifetime = _applicationServices.GetRequiredService
() as ApplicationLifetime; _hostedServiceExecutor = _applicationServices.GetRequiredService
(); var diagnosticSource = _applicationServices.GetRequiredService
(); var httpContextFactory = _applicationServices.GetRequiredService
(); var hostingApp = new HostingApplication(application, _logger, diagnosticSource, httpContextFactory); await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false); ...}

上述方法中HostingApplication实例最终被传入KestrelServer的启动方法中,这样才能在其内部调用HostingApplication的ProcessRequestAsync方法,并开始层层调用诸多的RequestDelegate方法。

public Task ProcessRequestAsync(Context context){    return _application(context.HttpContext);}

如果觉得使用Startup类还是有点麻烦的话,直接使用WebHostBuilder所提供的扩展方法也是同样的效果。

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>    WebHost.CreateDefaultBuilder(args)        .ConfigureAppConfiguration((hostingContext, config) =>        {            HostingEnvironment = hostingContext.HostingEnvironment;            Configuration = config.Build();        })        .ConfigureServices(services =>        {            services.AddMvc();        })        .Configure(app =>        {            if (HostingEnvironment.IsDevelopment())            {                app.UseDeveloperExceptionPage();            }            else            {                app.UseExceptionHandler("/Error");            }            app.UseMvcWithDefaultRoute();            app.UseStaticFiles();        });

不过使用独立的Startup类有着额外的好处,Startup类可以被包含在与Program类不用的的程序集中。然后通过WebHostOptions类中StartupAssembly属性的设定及其它相关处理,完成UseStartup方法同样的功能。

private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors){    ...    if (!string.IsNullOrEmpty(_options.StartupAssembly))    {        try        {            var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);            if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))            {                services.AddSingleton(typeof(IStartup), startupType);            }            else            {                services.AddSingleton(typeof(IStartup), sp =>                {                    var hostingEnvironment = sp.GetRequiredService
(); var methods = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName); return new ConventionBasedStartup(methods); }); } } ... } ... return services;}
posted on
2019-02-15 11:17 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/lonelyxmas/p/10382572.html

你可能感兴趣的文章
认识 service worker
查看>>
第五次团队作业:项目展示
查看>>
WIN10更新后,应用报“不能在此路径中使用此配置节。如果在父级别上锁定了该节,便会出现这种情况”...
查看>>
C#面向对象(二):封装和继承
查看>>
range()函数
查看>>
cs20_3-3
查看>>
codevs1074 食物链
查看>>
少量标签下的模型
查看>>
17.python购物车程序作业
查看>>
lightoj 1027【数学概率】
查看>>
Apparmor——Linux内核中的强制访问控制系统
查看>>
HOJ-1005 Fast Food(动态规划)
查看>>
jQuery 杂项方法
查看>>
系出名门Android(4) - 活动(Activity), 服务(Service), 广播(Broadcast), 广播接收 器(BroadcastReceiver)...
查看>>
Dynamics CRM Microsoft SQL Server 指定的数据库具有更高的版本
查看>>
C++学习基础九——继承
查看>>
android - anim translate中 fromXDelta、toXDelta、fromYDelta、toXDelta属性
查看>>
FasfDFS整合Java实现文件上传下载
查看>>
love2d教程5--摄相机1视角跟随玩家
查看>>
MonGoDB问题笔记
查看>>