How to create project templates in .net core

Often when developing software applications you’ll stumble across an effective approach to defining the structure and format for your projects. Especially when developing Microservices, your organisation may find that it will require to develop a number of services which all implement a consistent pattern, albeit that their implementations may vary.

A project template, can help teams to implement projects quickly. I must stress that sometimes it can be a fine line between creating a template and falling into the trap of developing a framework, often I have witnessed teams fall into this trap.

In Developing Api’s using HTTP Endpoints we seen how we could greatly improve our .net based API’s by making use of Clean Architecture approach. In that post we modified an existing Web API project template and installed a few nuget packages to get our project up and running. It would get pretty tiring and boring to have to do that everytime we wanted to create a new API project to that approach.

In this post, we develop a reusable project template to create our basic project structure for us with everything included out the box.

What is a dotnet project template

Programming frameworks typically have a templating system, which enable you to create new projects, files and methods etc quickly. The .NET Core SDK, incorporates a template system and most dotnet developers may already be familiar with it, because for the most part they will use to create a new dotnet project.

The .net core template system is exposed through the dotnet new terminal command , which provides a few options to tweak the output and select the type of project you want to create

Create a project

In our example, we’re going to first create a standard .net core web Api project, then we ‘re going to modify it to make use of the Ardralis API endpoints and also include a few other of my preferred libraries I like to use when developing API projects.

The default .NET Core SDK installation provides some initial templates and to list all the available templates, just run the following command with no parameters.

Shell

This will provide us with a list of all the available templates on our machine

In our example we’re going to initially make use of the Web API project template, so we’ll use the following command:

Shell

This will generate a standard Web Api Project with the familiar layout.

Our first step at this point is to Delete the Controllers folder and the WeatherForecast.cs because we won’t be needing them.

Then we will modify our ApiProject.csproj with content below, adding all my preferred libraries for developing Web API projects.

XML

We now want to create our sample project layout by providing an example of how to use it. I won’t go into too much here, about the files and folders we just added because I have discussed them in detail in Developing Api’s using Http Endpoints

In this project I have implemented to make use of the Vertical Slice Architecture

The next step we want to do is enable our configuration of Serilog, because we have added it as reference to our project. I have previously discussed implementing Serilog in .net core projects so I won’t discuss the intricacies here, but just provide the code we need to add to the Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog((hostContext, LoggerConfiguration) =>
                {
                    LoggerConfiguration.ReadFrom.Configuration(hostContext.Configuration);
                })
                .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
    }

We also want to update the StartUp.cs , the important points here is that we are wiring Mediatr and Serilog Request Logging.

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {Title = "ApiProject", Version = "v1"});
                c.EnableAnnotations();
            });
            services.AddMediatR(typeof(Startup));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSerilogRequestLogging();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiProject v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }

We have now essentially completed the initial implementation of our template project. We can run the project and ensure it all works. If we start our project we should get a browser window open up with our swagger endpoints being displayed

Create a template

We’ve now completed the grunt work of setting up project as to how we like, now we can start using it to create our template.

The first step to actually converting our project to a project template it to a a new folder to the root of our project folder and name it .template.config and inside that folder create a JSON file and name it template.json.

We need to add the following to our template.json to provide details about our template

JSON

The $schema value is always the same. This just tells compatible IDEs how to offer assistance when creating these documents. For example, Visual Studio Code will use the schema to offer some IntelliSense to us.

The author value is fairly self explanatory you can put any value you want in here i.e. Company Name, Person etc..

The classifications value is an array of descriptions you might use for your project. These are listed when you do dotnet new --list.

The identity value is a unique name for the template within the dotnet new list. You can use some sort of reverse-DNS notation or just about anything. (There seems to be a trend to put language in the last portion, but that is likely only needed if you have multiple language versions of a single template.)

The name value is the user-visible name for your template.

shortName value is the name people can use when creating projects from templates via command line, in the form of dotnet new {shortName}.

sourceName The name in the source tree to replace with the name the user specifies. The template engine will look for any occurrence of the sourceName mentioned in the config file and replace it in file names and file contents. The value to be replaced with can be given using the -n or --name options while running a template. If no name is specified, the current directory is used.

Top Tip

sourceName is important.

 dotnet new will replace all the folders/files/namespaces/etc.. containing this string with whatever the user passes in on the command line, using to -o or --output switch

Installing the template

At this stage our new template can easily be installed and used on our local machine to create new projects.

We can add our template to dotnet new template list simply by doing executing the following command in our terminal window.

Shell

This command will install the current directory (.) as a template. If your command line’s current directory is somewhere other than the template, you will need to adjust this accordingly.

We can now generate new projects based on our template simply by using the dotnet new command and the name of our template

Shell

Removing a Template

If you want to remove the template for whatever reason you can simply use dotnet new -u which will in turn list the templates and then also provide the instruction on how to remove the template you want.

In my case I simply want to use:

Shell

Distributing the template

The above example approach of managing and installing your template locally works great if you’re working on your own and are only creating templates for yourself. Usually though software developers work in teams, and you’ll often want to share your templates with other colleagues and teams.

A great way to share templates is via Nuget.org by packaging up your template as a nuget package.

To do this simply edit your .csproj file and add the following details. The most notable points would be to ensure that PackageType as been set to Template .

You also need to ensure you provide values for IncludeContentInPack , IncludeBuildOutput.

The rest of the values you should populate as you require.

XML

In our case we make use of Jetbrains TeamCity four our Continuous Integration so when committing a change to the Github Repository the code will be built, packaged and deployed to Nuget automatically.

We are also in the process of migrating from our Open Premise TeamCity to the TeamCity In the Cloud

https://github.com/threenine/api-template

Once the package is available on Nuget your team will be able to install it making use of the command provided on Nuget

Installing the template using

Shell

Will now enable us to generate a new project from the command line just as before, however we will now be making use of the template from Nuget which now can be shared with whoever would like to use it

Shell

Using templates in Rider

I predominantly use Jetbrains Rider Fast & powerful cross-platform .NET IDE for all my .net core development primarily because I only use Ubuntu Linux Desktop . After installing our template it now also becomes available in Rider so we can create new projects and solutions using the New Project/Solution dialog box

Conclusion

In this post we walked through the process of how to start creating your own customised project templates using .net core. We created our own template based on the Adralis API Endpoints, which I previously introduced in Developing Api’s using Http Endpoints, to enable a quicker and less tedious process of configuring projects to make use of it.

The  simplicity of the .net core packing and publishing tool, enables you simply use what you’re already doing to make doing what you’re already doing faster. No need to learn a new complex template language.

    Like this content ?

    Sign up to my newsletter and I'll send you updates and more!

    Latest posts by Gary Woodfine (see all)