asp.net core series 2 startup class Startup.CS

Life-long learning, excellence

The pendulum has swung back and Mo bully juvenile poor

Education represents your past, your ability to represent now, learning on behalf of your future

Before discussing Startup startup class, we start to understand the order of execution under Asp.NET CORE application configuration, as shown below

Comparison with earlier versions of ASP.NET, one of the most significant changes is to configure the application the way, Global.asax, FilterConfig.cs and RouteConfig.cs all gone, replaced by Program.cs and Startup.cs. Program.cs as the default entry in the case of Web applications, without any modification, calls ConfigureServices method and Configure method in the same directory Startup.cs.

 First we look at Progarm.cs, as follows

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
View Code

We see Program in the Main function much like the Console application before us, then it among CreateWebHostBuilder actually done anything yet? Since .Net Core is open source, we look at the source code on a lot of convenience, the next step down from its source to understand exactly what has been done.

/// <summary>
        /// Initializes a new instance of the <see cref="WebHostBuilder"/> class with pre-configured defaults.
        /// </summary>
        /// <remarks>
        ///   The following defaults are applied to the returned <see cref="WebHostBuilder"/>:
        ///     use Kestrel as the web server and configure it using the application's configuration providers,
        ///     set the <see cref="IHostingEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/>,
        ///     load <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostingEnvironment.EnvironmentName"/>].json',
        ///     load <see cref="IConfiguration"/> from User Secrets when <see cref="IHostingEnvironment.EnvironmentName"/> is 'Development' using the entry assembly,
        ///     load <see cref="IConfiguration"/> from environment variables,
        ///     load <see cref="IConfiguration"/> from supplied command line args,
        ///     configure the <see cref="ILoggerFactory"/> to log to the console and debug output,
        ///     and enable IIS integration.
        /// </remarks>
        /// <param name="args">The command line args.</param>
        /// <returns>The initialized <see cref="IWebHostBuilder"/>.</returns>
        public static IWebHostBuilder CreateDefaultBuilder(string[] args)
        {
            var builder = new WebHostBuilder();

            if (string.IsNullOrEmpty(builder.GetSetting(WebHostDefaults.ContentRootKey)))
            {
                builder.UseContentRoot(Directory.GetCurrentDirectory());
            }
            if (args != null)
            {
                builder.UseConfiguration(new ConfigurationBuilder().AddCommandLine(args).Build());
            }

            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;

                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }

                config.AddEnvironmentVariables();

                if (args != null)
                {
                    config.AddCommandLine(args);
                }
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
                logging.AddEventSourceLogger();
            }).
            UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            });

            ConfigureWebDefaults(builder);

            return builder;
        }
View Code
internal static void ConfigureWebDefaults(IWebHostBuilder builder)
        {
            builder.UseKestrel((builderContext, options) =>
            {
                options.Configure(builderContext.Configuration.GetSection("Kestrel"));
            })
            .ConfigureServices((hostingContext, services) =>
            {
                // Fallback
                services.PostConfigure<HostFilteringOptions>(options =>
                {
                    if (options.AllowedHosts == null || options.AllowedHosts.Count == 0)
                    {
                        // "AllowedHosts": "localhost;127.0.0.1;[::1]"
                        var hosts = hostingContext.Configuration["AllowedHosts"]?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        // Fall back to "*" to disable.
                        options.AllowedHosts = (hosts?.Length > 0 ? hosts : new[] { "*" });
                    }
                });
                // Change notification
                services.AddSingleton<IOptionsChangeTokenSource<HostFilteringOptions>>(
                            new ConfigurationChangeTokenSource<HostFilteringOptions>(hostingContext.Configuration));

                services.AddTransient<IStartupFilter, HostFilteringStartupFilter>();

                services.AddRouting();
            })
            .UseIIS()
            .UseIISIntegration();
        }
View Code

We can see from the source code, CreateDefaultBuilder task execution are:

  1, the host configuration table and loading the application information

  2, the configuration log

  3, set up a Web server

  4, is provided a hosted application Asp.Net Core.

Hosted application form Asp.Net Core, which hosted two forms: Managed hosting OutOfProcess outside InProcess process and in-process. We know Asp.Net Core is self-hosted, hosted its default form is InProcess. So what is the difference between these two methods is it?

InProcess: within the configuration process hosted .csproj project file <AspNetCoreHostingModel> InProcess </ AspNetCoreHostingModel>, in InProcess trusteeship, CreateDefaultBuilder () method call UseIIS () method and the IIS worker process (w3wp.exe or iisexpress.exe) in hosted application, from a performance perspective, InProcess hosting provides higher throughput than OutOfProcess hosting request.

OutOfProcess: There are two Web server - internal and external Web server Web server, internal Web server is Kestrel, the hosting process is dotnet.exe; external web server can be iis, nginx, apache.

In short, we can initially understood as Program.cs is mainly used to construct, configure, and enable the project depends server, and finally set up a hosted Asp.Net Core applications.

In Program.cs, we found that references Startup.CS, as follows:

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

Let us look at the startup class Startup.CS, as follows:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                //如果是开发环境,允许抛出异常
                app.UseDeveloperExceptionPage();
            }
            else
            { 
                // production environments, direct error page 
                app.UseExceptionHandler ( " / Error " ); 
                app.UseHsts (); 
            } 

            app.UseHttpsRedirection (); 
            app.UseStaticFiles (); 
            app.UseCookiePolicy (); 

            app.UseMvc (); 
        } 
    }
View Code

Startup class action:

  1. ConfigureServices process for the service definition (registered) used by the application. (Such as: ASP.NET Core MVC, Entity Framework Core, Identity, etc.);

  2. Configure method for defining a middleware request pipeline, the pipeline will be used for all requests processing applications.

  3. Add the registrar is disordered, ASP.NET Core when the application starts, as long as there is a corresponding service can be, and middleware registration method is ordered, each component within the pipeline can choose whether the request to the next component, and perform some action before the next component in the pipeline or after a call.

1. ConfigureServices

Application by  ConfigureServices adding service. Then, host and application services are in  Configure use and throughout the application.

In other words  ConfigureServices , we ...

In NETCORE, depending injection almost everywhere,

 

Unfinished, continued ... work, and Hungry Ghost Festival, should not be too much overtime.

 

Guess you like

Origin www.cnblogs.com/chenwolong/p/Startup.html