If you are following ASP.NET Core 6, then probably you are aware that with ASP.NET Core 6.0 projects, there is no Startup.cs
file. It is now combined with Program.cs
file to bring unified experience. I posted about How to Add Startup.cs in ASP.NET Core 6 Project and this approach brings Startup.cs
class in the project in a traditional way that we have today with ASP.NET Core 5 and it’s prior version. But what if we can improve things and make it better. Well, in this post, let’s take a look at a clean way to add Startup class in ASP.NET Core 6 projects.
Clean way to add Startup class in ASP.NET Core 6
To implement in a clean way, we’ll leverage Extension methods. The extension methods allows you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. ASP.NET Core 6.0 uses WebApplicationBuilder
and WebApplication
to bootstrap an ASP.NET Core application. So we’ll create extension method for these classes.
Remember, these 2 are newly introduced with ASP.NET Core 6. Read Comparing WebApplicationBuilder to the Generic Host and Exploring the code behind WebApplicationBuilder to know more about this new bootstrapping model.
The WebApplicationBuilder
class is used for register/configure the services or dependencies. As Extension methods are static methods, so create a static class RegisterStartupServices
with a static method named RegisterServices
. Now, move the dependency registration code from Program.cs
and bring it here. Like,
Now, let’s create another static class RegisterStartupMiddlewares
which extends the WebApplication
class used for middleware registration. In this class, move the middleware registration code from Program.cs
and bring it in SetupMiddleware
method. Like,
Once this is done, let’s go back to our Program.cs
to update the code and use these extension methods. Like,
Or, we can further clean it and make it in one line. Like,
Now, this looks more clean, readable and manageable. That’s it.
Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.
One thought to “Clean way to add Startup class in ASP.NET Core 6”