Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build your own .NET Core project template

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to build their own .NET Core project template, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to know about it.

Preface

Create your own project template based on dotnet cli, also known as scaffolding.

Dotnet cli project template warm-up

Before we get to the point, let's take a look at some templates that come with dotnet cli.

You can see that there are still many kinds, and since I spend most of my time writing WebAPI, I'll use WebAPI to write a simple template here.

Let's write our own template based on dotnet cli.

Write your own template

Since it is a template, there must be a sample project.

Let's build a sample project, which is roughly like this, and everyone can do it according to their own habits.

This is actually an ordinary project, which adds components such as NLog,Swagger,Dapper, and the reference relationship of each project is established.

It also contains all the public classes that should be available, such as the WebHostBuilderJexusExtensions shared by Unochi.

Here is the effect of this template running.

It's a simple Swagger page.

Now that you have an example, how do you turn it into a template?

The answer is template.json!

Create a folder .template.config in the root directory of the sample, and create a template.json under this folder.

Examples are as follows:

{"author": "Catcher Wong", / / must be "classifications": ["Web/WebAPI"], / / must be, the Tags "name" of the corresponding template: "TplDemo", / / must, the Templates "identity" of the corresponding template: "TplDemoTemplate", / / optional, the unique name of the template "shortName": "tpl", / / must be The Short Name "tags" of the corresponding template: {"language": "C #", "type": "project"}, "sourceName": "TplDemo", / / optional, the name to be replaced "preferNameDirectory": true / / optional, add directory}

Here, there are several more important things, one is shortName, the other is sourceName.

ShortName, abbreviated, necessary to be lazy, just like if you can write-h, you will never write-- help.

SourceName, which is an optional field, whose value replaces the specified project name, which is normally assigned here. If not specified, the project created is consistent with the sample project.

After writing template.json, we also need to install this template into our cli.

Use dotnet new-I to install the template.

The following is an example of an installation.

Dotnet new-I. / content/TplDemo

Note here that directories at the same level as the .template.config folder are packaged into the template.

After executing the installation command, you can see that our template has been installed.

I can't wait to try this template at this time.

Let's take a look at the help information for this template first.

Dotnet new tpl-h

Because we haven't set the parameters yet, what's shown here is that there are no parameters yet.

Let's try to create a project.

From creating a project to running it, it is very simple, and the effect is what we expect.

Let's see if the directory structure of the new HelloTpl project is the same as our template.

As you can see, except for the name, everything else is the same.

Do you feel like you can copy and paste a lot of code again?

Although, now the construction project, has been able to put a large template of the complete copy out, but it is not very flexible!

Some friends may ask, why would you say it is inflexible when it is already very convenient?

Just listen to me slowly.

If this template is a large and comprehensive template, including middleware A, middleware B, middleware C and other N middleware!

When building a new project, it has been made clear that only middleware An is used, so other middleware may not have much meaning for us!

Most of the time, you don't want these extra files to appear in the code, is there any way to control it?

The answer is yes! You can just rule out unwanted files.

File filtering

There is a RequestLogMiddleware in the template project, so use it as an example.

We just need to do the following things.

The first step is to add a filter to template.json

Add a symbol named EnableRequestLog. Specify the source file at the same time

{"author": "Catcher Wong", / / others... "symbols": {/ / whether to enable the Middleware "EnableRequestLog" of RequestLog: {"type": "parameter", / / it is the parameter "dataType": "bool", / / the parameter of bool type "defaultValue": "false" / / does not enable}} by default, "sources": [{"modifiers": [{"condition": "(! EnableRequestLog)" / / conditions The "exclude" is determined by the EnableRequestLog parameter: [/ / exclude the following files "src/TplDemo/Middlewares/RequestLogMiddleware.cs", "src/TplDemo/Middlewares/RequestLogServiceCollectionExtensions.cs"]}}]}

Second, do some processing in the code of the template

Mainly Startup.cs, because this is where Middleware is enabled.

Using System; / / other using... Using TplDemo.Core;#if (EnableRequestLog) using TplDemo.Middlewares;#endif / / public class Startup {public void Configure (IApplicationBuilder app, IHostingEnvironment env) {/ / other code....#if (EnableRequestLog) / / request Log app.UseRequestLog () # endif app.UseMvc (routes = > {routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}";});}}

In this way, as long as EnableRequestLog is true, you can include these two pieces of code.

Let's update the template that has been installed.

At this time, if you look at its help information, you can already see the parameters we added.

Let's first create a default (do not enable RequestLog)

Dotnet new tpl-n NoLog

This command is equivalent to

Dotnet new tpl-n WithLog-E false

Here is the directory structure and Startup.cs after it is built.

You can see that everything related to RequestLog is gone.

Build another one that enables RequestLog and see if it really works.

Dotnet new tpl-n WithLog-E true

As you can see, the effect has already come out.

Here is a useful feature. Dynamic switching, this is actually similar to the content introduced above.

Dynamic switching

Let's just give an example to illustrate.

Suppose our template supports four database operations: MSSQL, MySQL, PgSQL and SQLite.

When you build a new project, you only need one of them, for example, if you want to build a PgSQL, you certainly don't want to see the other three.

I don't want to see here that there are two places, one is the reference to the nuget package, and the other is the code.

The previous section is about a specific function of the switch operation, here are 4, how do we deal with it?

We can do this with a parameter of type choice.

Modify the template.json to add the following

{"author": "Catcher Wong", / / others "symbols": {"sqlType": {"type": "parameter", "datatype": "choice", "choices": [{"choice": "MsSQL", "description": "MS SQL Server"}, {"choice": "MySQL", "description": "MySQL"} {"choice": "PgSQL", "description": "PostgreSQL"}, {"choice": "SQLite", "description": "SQLite"}], "defaultValue": "MsSQL", "description": "The type of SQL to use"}, "MsSQL": {"type": "computed", "value": "(sqlType =\" MsSQL\ ")"} "MySQL": {"type": "computed", "value": "(sqlType =\" MySQL\ ")"}, "PgSQL": {"type": "computed", "value": "(sqlType = =\" PgSQL\ ")"}, "SQLite": {"type": "computed", "value": "(sqlType = =\" SQLite\ ")"}

After reading the JSON content above, I believe you all know why. There is a parameter called sqlType, which has several database choices, and the default is MsSQL.

In addition, several computational parameters are defined, and their values are closely related to the value of sqlType.

MsSQL,MySQL,PgSQL and SQLite are four parameters that we also need to use in the code!

Modify the csproj file so that it can dynamically reference the nuget package based on sqlType. Let's add the following

Similarly, the code has to be handled accordingly.

# if (MsSQL) using System.Data.SqlClient;#elif (MySQL) using MySql.Data.MySqlClient;#elif (PgSQL) using Npgsql;#else using Microsoft.Data.Sqlite;#endif protected DbConnection GetDbConnection () {# if (MsSQL) return new SqlConnection (_ connStr); # elif (MySQL) return new MySqlConnection (_ connStr); # elif (PgSQL) return new NpgsqlConnection (_ connStr); # else return new SqliteConnection (_ connStr); # endif}

After the modification, you also have to reinstall the template, and after installation, you can see the parameter sqlType.

Let's create a project for MsSQL and PgSQL for comparison and verification.

Execute successively

Dotnet new tpl-n MsSQLTest-s MsSQL dotnet new tpl-n PgSQLTest-s PgSQL

Then open the corresponding csproj

You can see that the NPgsql package has been added to PgSQL. But MsSQL's didn't.

Similarly, DapperRepositoryBase has the same effect. When creating Connection objects, they are generated according to the template.

Of course, this is a template installed locally by ourselves, and no one else can use it.

If you want to make it public, you can post it to nuget. If it is shared within the company, you can build an internal nuget service and upload the template to the internal server.

Thank you for reading this article carefully. I hope the article "how to build your own .NET Core project template" shared by the editor will be helpful to you. At the same time, I also hope that you will support and follow the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report