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 Program.csfile 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.

comments powered by Disqus

Related