Asp.net Startup.cs Class

  • by

There are two methods associated with the Startup.cs file which are called during the run-time.They are

  1. ConfigureServices Method
  2. Configure Method

Though the Main method in Program.cs file is actually where the application starts executing from, the actual configurations set up and the wiring of services is done in the Startup file. We can also say that the actual entry point to the application is the Startup file.

As mentioned before, there are two main things that a Startup class can perform

  1. Wiring up of services 
  2. Create the app’s request processing pipeline

These two functionalities are taken care of by ConfigureServices and Configure methods respectively.

Before we dig deep into these methods, let’s look into the constructor in the StartUp. When we created the dotnet core app through command line, the constructor of the StartUp looks something like the following,

public Startup(IConfiguration configuration)

       {

           Configuration = configuration;

       }

Here it takes in IConfiguration as an argument, along with this there are two more possible arguments that can be added depending on our requirements. They are IWebhostEnvironment and IHostEnvironment.

  1. IConfiguration, as mentioned before, can be used to load the configuration file from the possible sources. It is a key value pair of the application configuration. 
  2. IWebHostEnvironment provides information about the web hosting environment in which the app is hosted and running.
  3. IHostEnvironment provides information about the hosting environment in which the app is hosted and running. This is similar to IWebHostEnvironment in fact, this was created as an abstraction to the IWebHostEnvironment. To know more on why you can refer to the following link https://andrewlock.net/ihostingenvironment-vs-ihost-environment-obsolete-types-in-net-core-3/

It is also possible to have multiple Startup files for the same application for different environments, and the corresponding Startup file is selected during the run time. When there is a Startup file and a StartupDevelopment file the preference is given to the StartupDevelopment file. Check the following link for more information on the multiple Startup files https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-5.0#environment-based-startup-class-and-methods 

Host

When the App starts up the dotnet core builds a host.The main intent of the StartUp file is to build this host with the appropriate information for running the application. As we have discussed before the things that are required for running the application are,

  1. HTTP server implementation
  2. Middleware components
  3. Logging
  4. Dependency Injection
  5. Configuration

The host is an object returned from the Startup class, that encapsulates all this information.

Now let’s journey back to the two methods that we were talking about,these methods are responsible for encapsulating the host with the above mentioned information.

ConfigureServices Method

Dotnet core uses Dependency injection to make the services available across the application. Hence whenever we create a service it is necessary to add it here, so that it becomes available throughout the application.And when another service has a dependency it is just enough if we mention it in the constructor of the service.

This method is also used to fetch the configuration information from the actual config files.

This method takes an IServiceCollection object as an argument where all the services that are created as part of our application are registered. There are many methods associated with IServiceCollection, few of which we will see in the following sections.When we have created the default web api app through CLI, the ConfigureServices method will look something like the following,

public void ConfigureServices(IServiceCollection services)

       {

           services.AddControllers();

       }

This AddControllers method will basically register all the services that are commonly used for a controller in MVC.Meaning, this method just focuses on the C part of the MVC. This method returns an IMvcBuilder which allows us to add some additional services. 

Also for features that require some basic set ups during the start of the application, such as initialising DB context etc, IServiceCollection provides Add{Service} extension methods. For example, AddDbContext, AddDefaultIdentity etc.When the services are provided in this method, it is resolved via dependency injection.

Now let’s come to the configuration part that can be set as part of this method. This method can be used to bind particular part config to the configuration by adding it to the service container.

Configure Method

Now that we have created our app using the command line commands, the configure method in startup by default will be,

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

       {

           if (env.IsDevelopment())

           {

               app.UseDeveloperExceptionPage();

           }

           app.UseHttpsRedirection();

           app.UseRouting();

           app.UseAuthorization();

           app.UseEndpoints(endpoints =>

           {

               endpoints.MapControllers();

           });

       }

The application that we have created is of web api type. The client requests are either Http/Https requests. There are controllers that are going to handle these http requests accordingly. But before these requests hit the controller, they go through some layers of middleware that run on top of the controller logic. Some of these middlewares are related to the Exception handling, Http requests etc are specified as part of this method. These are called request pipelines and they are executed for every request.

We can see that there are multiple methods called here.

  1. The UseDeveloperExceptionPage method handles the exceptions that occur when the request hits the controller and all the execution takes place and this returns a http response based on the exception.
  2. UseHttpRedrection method , redirects the http requests to https requests so that it’s more secure since the request can be of both types from the client side.
  3. UseRouting method, this method is responsible for adding the EndpointRoutingMiddleware to the app builder. This middleware is where the routing decisions are made and the appropriate endpoint is associated with the httpcontext.This method should always be followed by the UseEndpoints method
  4. UseAuthorization this adds the middle ware to authorize the requests that come in.
  5. UseEndpoints, this method adds the EndpointMiddleware. Here is where the endpoints associated with the http context are executed.

To learn more about the configure method https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-5.0

Leave a Reply

Your email address will not be published.