Reducing Boilerplate Code in .NET Applications with Command Line Switches
Over the past few years, I’ve been using Visual Studio less and less, preferring VS Code, and more recently Rider.
I also use the command line more than in the past for project creation, running the application, testing, etc. Regarding project creation, I use the command line switches to fine-tune the project, and how it works.
Sometimes I want top-level statements, sometimes I want the old-style
file with aMain` method.
I often don’t want API documentation, HTTPs redirection, etc.
You could use
dotnet new webapi, and then trim out what you don’t want.
But there is an easier way. Try this to see all the options -
dotnet new webapi --help
For simple things I use -
dotnet new webapi --no-https --no-openapi -n MyWebApi
This reduces the
Program.cs from 14 to 6 lines of code.
Other useful switches are -
--use-minimal-apis // Use minimal APIs instead of controllers
--use-program-main // Use a traditional Main method instead of top-level statements
Keep in mind, all templates have a variety of switches available.
- A Web Server that Echoes Requests and Sometimes Faults with a 500 Error
- A Simple Web API Application that Echoes the Request for any URL
- Using MediatR with API Endpoints
- Dependency Injection of a Type within Program.cs Using Top Level Statements
- Dependency Injection of an Entity Framework Context within Program.cs Using Top Level Statements