How to keep startup file lean and clean in Dotnet core
If you are reading this you are already using Asp.Net Core and the Startup file is your go-to place to register dependencies, setting up third-party dependencies, and configure your app behavior.
One file and so many responsibilities 🤔
If your Startup file contains more than 100 lines of code then you really need to think it through and make it leaner and cleaner.
Why should I care?
- First of all, it is harder to read and maintain lengthy files
- It's not very organized and it is tough to find related things
- With time and increase in the code base, the startup file becomes the God file
- It’s hard to set up a convention for the junior developers or new joiners in the team
- It’s violating the Single Responsibility Principle
Making Startup file lean and clean
Let’s take a peek into a God Startup file
If your startup file looks similar to the above one then it’s time to do some cleaning.
There’s nothing wrong with having a startup file shown here but the real problem arises when your codebase starts to become bigger and more developers join the team.
Extension Method to the rescue
The simple technique to make startup file lean is to use extension methods. Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
We can create separate extension methods to have specific functionalities like we can create one extension method to keep all code related to authentication, similarly, one method to have all the swagger-related code.
Let’s do some cleanup
Creating extension methods to register services/repositories dependencies:
Typically a web project contains separate dll projects for repository and services. Both the projects can contain their own Startup.cs file that can be used to register dependencies
Let’s create separate Startup files for Repository and Services in their respective projects.
Create a Startup to register repository dependencies:
Create a Startup to register services dependencies:
Let’s also create a Swagger extension method to move all the swagger-related configurations.
What we did so far is simple, we just split the one startup into multiple startups with their responsibilities.
Let’s see the final version of the original startup.cs:
Improvements:
- Reduce no of using statements (namespaces)
- Better readability
- Separation of responsibility
Final Words
The code shown is very simple and you must be already doing it but I know there are people who still struggle with lengthy startup files and my suggestion to them is just take a little and start cleaning up as it is very simple to achieve with minimum efforts.