• Fri. Oct 25th, 2024

Demystifying the Program and Startup classes in ASP.NET Core

Byadmin

Jan 6, 2022


ASP.NET Core 6 introduces a simplified hosting model that reduces the boilerplate code that you would otherwise need to write to get your ASP.NET Core application up and running. The Program and Startup classes are the two major classes where you would typically write your code to configure your application.This article talks about how you can configure the application start-up classes in ASP.NET Core 6, with relevant code examples wherever appropriate.To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.Create an ASP.NET Core Web API project in Visual Studio 2022First off, let’s create an ASP.NET Core project in Visual Studio 2022. Following these steps will create a new ASP.NET Core Web API 6 project in Visual Studio 2022:
Launch the Visual Studio 2022 IDE.
Click on “Create new project.”
In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
Click Next.
In the “Configure your new project” window, specify the name and location for the new project.
Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
Click Next.
In the “Additional Information” window shown next, select .NET 6.0 as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default).
Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be using any of those features here.
Click Create.
This will create a new ASP.NET Core 6 Web API project in Visual Studio 2022. We’ll use this project in the subsequent sections of this article.What is a host in .NET and .NET Core?A .NET or .NET Core web application runs inside a host that handles application startup, web server configuration, etc. The host encapsulates resources such as logging, configuration, dependency injection (DI), and any IHostedService implementations. A host is created, configured, and executed using the code written in the Program class. To create a host in ASP.NET Core 6, you should call the Build().Run() method on a host builder. A host builder is an instance of IHostBuilder. The following code snippet illustrates this:var builder = WebApplication.CreateBuilder(args);var app = builder.Build();app.Run();The WebApplication class implements the following interfaces:
IHost – used to start and stop the host
IApplicationBuilder – used to build the middleware pipeline
IEndpointRouteBuilder – used to add endpoints
You can also call the CreateDefaultBuilder method to create a host. This method is used to initialize a new instance of the WebHostBuilder class with pre-configured defaults.The following code snippet shows how the CreateDefaultBuilder method can be used:var host = new WebHostBuilder()      .UseKestrel()      .UseContentRoot(Directory.GetCurrentDirectory())      .UseIISIntegration()      .UseStartup<Startup>()      .Build();Note that both WebApplication and WebApplicationBuilder classes were introduced in ASP.NET Core 6.The ConfigureWebHostDefaults() extension method can be used to configure a web application host by selecting Kestrel as the web server and configuring it using the application’s hosting configuration providers. The Program class in .NET and .NET CoreA .NET or .NET Core project needs an entry point to start. The Main() method is the entry point in a .NET or a .NET Core application. Because Main() is the entry point of your application, you can have one and only one Main() method in your project. Although you can put Main() anywhere in your project, it is typically located in a class named Program, stored in a file called Program.cs.The Program class in ASP.NET Core 5Here is how a minimal Program class would look in .NET 5:public class Program{      public static void Main(string[] args) {            CreateHostBuilder(args).Build().Run();      }      public static IHostBuilder CreateHostBuilder(string[] args) {            return Host.CreateDefaultBuilder(args).            ConfigureWebHostDefaults(x => x.UseStartup <Startup> ());      }}The Program Class in ASP.NET Core 6When you create a new Web API project in ASP.NET Core 6, you will have a Program.cs file. However, unlike in ASP.NET Core 5 (and all previous versions of ASP.NET Core), the project will not generate a Startup.cs file. The default generated code of the Program class in ASP.NET Core 6 will look like this:var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllers();var app = builder.Build();// Configure the HTTP request pipeline.app.UseAuthorization();app.MapControllers();app.Run();The Startup class in .NET and .NET CoreThe Startup class contains the ConfigureServices and Configure methods. While the former is used to configure the required services, the latter is used to configure the request processing pipeline. The Configure method is executed immediately after the ConfigureServices method. Both of these methods are called by the runtime when the application starts. At runtime, the .NET host passes an instance of IApplicationBuilder to the Configure method. By default, the ConfigureServices adds the services to the built-in container.The following code listing illustrates how the Startup class is organized:public class Startup  {        public void ConfigureServices(IServiceCollection services)        {            //Write code to add services to the container here        }        public void Configure(IApplicationBuilder app)        {         //Write code here to configure the request processing pipeline        }      //Other members have been removed for brevity   }You would also have a constructor in the Startup class which would be used to initialize an IConfiguration instance, as illustrated in the code listing in the next section.Use the Startup class in ASP.NET Core 6Although the Startup class is not generated by default in ASP.NET Core 6, you can use the Startup class in ASP.NET Core 6 if you want to. To do this, you should create a class named Startup (you can specify any other name as well) and enter the ConfigureServices and Configure methods as shown below.  public class Startup  {        public Startup(IConfigurationRoot configuration)        {            Configuration = configuration;        }        public IConfigurationRoot Configuration { get; }        public void ConfigureServices(IServiceCollection services)        {            services.AddControllers();        }        public void Configure(IApplicationBuilder app)        {            app.UseRouting();            app.UseEndpoints(x => x.MapControllers());        }   }The UseRouting and UseEndpoints methods are used to add and configure the routing middleware to the request processing pipeline. Your Program class code should refer to the newly created Startup class. To do this, replace the existing code of the Program class with the following code:var builder = WebApplication.CreateBuilder(args);var startup = new Startup(builder.Configuration);startup.ConfigureServices(builder.Services);var app = builder.Build();startup.Configure(app);app.Run();Now set a breakpoint in the ConfigureServices and Configure methods of the Startup class we created earlier. You’ll observe that the breakpoints are hit when you run the application.The new minimal hosting model in ASP.NET Core 6 enables you to write less boilerplate code to get your application up and running. To maintain backward compatibility, you can still use the Startup class in ASP.NET Core 6. You can read more about the minimal hosting model in my previous article here.

Copyright © 2022 IDG Communications, Inc.



Source link