DEV Community

Cover image for Cleaning Up The Program.cs File In ASP.NET 6 (API,MVC)
Hesham mohamed
Hesham mohamed

Posted on

Cleaning Up The Program.cs File In ASP.NET 6 (API,MVC)

We know that there are differences in ASP.NET 6 from the previous ones, and among these differences is that they merged the two files (Startup.cs - Program.cs) and put them in the Program.cs file. In this article, I will talk about how to improve the Program.cs file in a nice way and clear for programmers.
First, here is an example of the program.cs file in ASP.NET 6:

Image description

The (WebApplicationBuilder) class is used for register/configure the services or dependencies. As Extension methods are static methods, All we need to do is create a folder and we call for example (Installer), and create two files in it The first file we call it for example (RegisterDependentServices) And move the dependency registration code from Program.cs and bring it here. as follows:

Image description

The second file we call it for example (SetupMiddlewarePipeline) And move the middleware registration code from Program.cs as follows:

Image description

After that update the Program.cs and use these extension methods (RegisterServices and SetupMiddleware) So the Program.cs file becomes as follows:

Image description

Now the code look readable, manageable and nice.
Thank you for reading the article and Iā€™m waiting for your comments

Top comments (0)