Explain the purpose of the Program class in ASP.NET Core


An ASP.NET Core application starts similarly to a .NET Console application. It uses the Main() method defined in the Program.cs file as the entry point of the application. The framework calls the Main() method whenever you start the web application.

In the ASP.NET Core application, the Main() method builds and runs the Host. The Host object is one of the essential parts of the ASP.NET Core application. It contains the configuration and the webserver (Kestrel) that your application uses.

Program.cs

Here is a sample Program.cs file in a standard ASP.NET Core application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace TutorialsPoint{
   public class Program{
      public static void Main(string[] args){
         CreateHostBuilder(args).Build().Run();
      }
      public static IHostBuilder CreateHostBuilder(string[] args) =>
         Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>{
               webBuilder.UseStartup<Startup>();
            });
   }  
}

In the above example,

  • The CreateHostBuilder() method creates an IHostBuilder instance using the default configuration.

  • ConfigureWebHostDefaults() uses the WebHostBuilder object to configure the application to use Kestrel.

  • CreateDefaultBuilder() is a static helper method to simplify the creation of the application by creating an IHostBuilder with the standard configuration.

  • UseStartup<Startup> tells the framework to use the Startup.cs class for configuration.

  • Once the IHostBuilder is configured, the Build() method creates and returns an instance of IHost from the IHostBuilder. However, the application still isn't listening for requests.

  • The Run() method runs the IHost and listens for HTTP requests.

As you can see, the Program class provides the initialization code to create a web host and listen to incoming requests. Most of the boilerplate ASP.NET Core configuration happens in the CreateDefaultBuilder() method. The Startup.cs class handles the application-specific configuration, i.e., the services required by your application middleware pipeline.

Typically, you won't change the Program class once the application starts growing, whereas you'll frequently be modifying the Startup class to add/remove services that your application needs.

Updated on: 22-Jun-2021

559 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements