Creating custom templates for dotnet new

Posted: (EET/GMT+2)

 

If you find yourself creating the same kind of C# projects repeatedly, a custom dotnet new template can save time and keep new projects consistent.

These kind of custom templates are useful when you always want the same starting point: the same folder structure, package references, configuration files, logging setup, analyzers, or test projects. The .NET template engine supports custom templates by adding a .template.config/template.json file to an existing project or folder and then installing that template for local use.

The easiest way to start is to take an existing project that already looks the way you want, and then turn that into a template.

Here is an example structure for a template:

MyTemplate\
  MyTemplate.csproj
  Program.cs
  appsettings.json
  .template.config\
    template.json

The key file is .template.config\template.json. That file defines the template name, short name, and other metadata used by dotnet new.

For example:

{
  "$schema": "http://json.schemastore.org/template",
  "author": "Your Name",
  "classifications": [ "Common", "C#" ],
  "identity": "MyCompany.ConsoleTemplate",
  "name": "My Company Console App",
  "shortName": "myconsole",
  "sourceName": "MyTemplate"
}

In this example, the sourceName property tells the template engine which name in the source files should be replaced when a new project is created. That makes it easy to use one sample project as the starting point for many new projects.

To install a template from a local folder, use the dotnet new install command as follows:

dotnet new install C:\Templates\MyTemplate

After this, you can list installed templates and create a new project from your custom one:

dotnet new list
dotnet new myconsole -n MyDemoApp

The current dotnet new command supports the list option to show installed templates, and the install is used to install a template package or local template source.

A few practical tips when creating your own templates:

  • Start with a real project that already works.
  • Keep the first version simple. One good internal template is more useful than a very flexible that nobody has the time to maintain.
  • Add the common things you always need, such as analyzers, logging packages, test setup, or company-wide configuration files.
  • Run dotnet new details <shortName> to check the template options after installation.

If you want to share the template with others, you can also package it and install it as a template package. The .NET template system supports creating and distributing template packages for reuse.

So, the practical idea is simple: if you keep creating the same project skeleton by hand, stop doing that. Create one good project, turn it into a dotnet new template, and reuse it.

Example templates can be found from Microsoft's GitHub repo.