1 Introduction

The default startup class named Startup, it is in order to construct a program entry point IWebHost through UseStartup<Startup>()specified. Mainly defined two methods ConfigureServiceand Configuremethods. The application starts with UseStartupa Startupclass or assembly specified by the method , with StartupLoadera reflective call to complete the dependency service registration and middleware registration to construct a complete HTTP request pipeline.

Let’s explore the simple usage of the Startup class in the MVC template project.

2. Convention method

We know that start class consists mainly ConfigureServiceand Configuretwo methods.

2.1. ConfigureService

This method is typically used by the configuration service to register the service into the dependency injection container, which Configureis called before the method. IServiceCollectionService registration is performed by the extended method called . The naming proposal for the extension method is based on Add[MethodName] , such as the registration of Mvc related services services.AddMvc().

In addition, we can also replace the default built-in dependency injection framework of ASP.NET Core in this method. For example, we use Castle Windsor to replace:

  1. Install the Castle.Windsor.MsDependencyInjection NuGet package;
  2. Modify method return value type is IServiceProvider;
  3. Replace the dependency container:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    //Add Castle Windsor DI
    var ioContainer = new WindsorContainer();

    return WindsorRegistrationHelper.CreateServiceProvider(ioContainer, services);
}

2.2. Configure

This method is used to define how the application responds to each HTTP request and to configure middleware in the HTTP pipeline.

public void  Configure(IApplicationBuilder app)   
{  
    app.UseMvc();  
    app.Run( context => {  
        return  context.Response.WriteAsync("Hello ASP.NET Core!");  
    });  
} 

This method accepts IApplicationBuilderas a parameter and accepts some optional parameters such as IHostingEnvironmentand ILoggerFactory. Moreover, ConfigureServicesother services registered in the method can also be directly injected into the method directly through the parameters, such as:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<ITestService, TestService>();
}

public void Configure(IApplicationBuilder app,ITestService testService)
{
    testService.Test();
}

Because this method is used to configure the entire http request pipeline, the registration of middleware should pay attention to the order . Similarly, when configuring middleware, we also recommend following the naming convention of Use[Middleware] , such as enabling Mvc middleware app.UseMvc.

3. Available services

As we learned from the previous section, ASP.NET Core has injected the following available services by default before calling:

  • IConfiguration: Used to read the application configuration.
  • IServiceCollection: can be understood as a dependency injection container built into ASP.NET Core.
  • IApplicationBuilder: The request pipeline used to build the application.
  • IHostingEnvironment : Provides the host environment configuration information for the current application’s operation.

In addition, we can also use the services that have been injected IServiceProvider, ILoggerFactory, ILoggerand so IApplicationLifetimeon. These preset services can be injected into the constructor or Configuresquare of the Startup class . like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
      ILoggerFactory loggerFactory)
{
      loggerFactory.AddDebug();
}

ConfigureServicesOnly one parameter is supported IServiceCollection, because all dependencies can be IServiceCollectionobtained, so there is no need to inject other services through the method. You can directly resolve the dependent services in the following ways:

public void ConfigureServices(IServiceCollection services)
{
    var serveiceProvider = services.BuildServiceProvider();
    var logger =serveiceProvider.GetService<ILogger>();
    //....
}

4. Define multiple startup classes

Looking at the Configuremethod we found, through the IHostingEnvironmentservice, we can get the running environment of the current application. In the code, the exception details page, database error page and Brower Link (supporting multiple web browsers, and synchronous refresh, generally used for cross-browser testing) are enabled for the development environment, so that we can develop and debug.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    //...
}

ASP.NET Core has three built-in environment variables by default: Development, Staging, and Production. We can define a startup class for each environment, named Startup[Environment]. The ASPNETCORE_ENVIRONMENTcorresponding startup class can be automatically loaded according to the configuration in launchSettings by specifying the assembly name of the startup class at startup.

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup(Assembly.GetExecutingAssembly().FullName)
        .Build();

ASP.NET_Core__basic_series(3)_startup_class_1.png

Example

Orignal link:https://www.jianshu.com/p/712bd0e6d1d9