40

ASP.NET 自定义项目模板 | Beck's Blog

 4 years ago
source link: http://beckjin.com/2019/08/04/aspnet-template/?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

.NET 自定义项目模板(一):快速入门

2019-08-04

| .NET

|

在微服务架构盛行的时代,一言不合就新建一个服务,虽然搭建服务并没什么难度,但不可避免的是每个人搭建出来的架子会存在差异,这很合理,因为每个开发者的个人风格、工作经验都不一样,难免认为自己喜欢的才是最好的。另一方面,如果需要较频繁搭建服务,这些重复而没难度的操作就显得浪费时间,而且每次手动处理总可能存在一些细节上的失误,出现异常然后花时间解决更得不偿失。

面对以上一些问题,拥有一个符合自己团队的项目模板就显得比较重要了,这篇文章主要介绍在 .NET 如何自定义项目模板。

内置的项目模板

在 VS 中,新建项目时我们都需要先选项目类型,这些类型选项本质上是内置的项目模板,不同类型对应不同的项目代码结构。

通过命令查看当前有的项目模板:

1
dotnet new -h

内置的项目模板

以上是内置的一些项目模板,如 consoleclasslibmvcwebapi 等应该都是平时使用比较多的。

创建项目模板

  1. 搭建项目 (这里是只是 Demo 例子,实际根据自己的项目要求自定义项目结构)

    DemoService
    • 新建一个 .NET Core Web API 项目(DemoService.API) 和 .NET Standard 类库(DemoService.Core);
    • DemoService.API 引用 DemoService.Core;
    • DemoService.API 添加 Swashbuckle.AspNetCore 生成 Swager 文档的引用;
    • DemoService.Core 添加 ServiceStack.OrmLite.SqlServer 数据库操作的 ORM 库引用;

      这一步和搭建普通的项目没任何区别,搭建完成后可测试看看效果。

  2. 添加模板配置

    在解决方案 .sln 所在的目录下创建模板配置文件夹 .template.config,并在 .template.config 文件夹下创建 template.json 文件,编辑 template.json,输入以下配置:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    {
    "$schema": "http://json.schemastore.org/template",
    "author": "Me",
    "classifications": [ "micro", "webapi" ],
    "identity": "DemoService",
    "name": "DemoService",
    "shortName": "swa",
    "tags": {
    "language": "C#",
    "type": "project"
    },
    "sourceName": "DemoService",
    "preferNameDirectory":"true"
    }

    配置说明:

    • author:模板作者,必填
    • classifications:模板分类,必填
    • name:模板名称,当使用 dotnet new 创建项目时,指定的模板名称,必填
    • identity:模板唯一名称,必填
    • shortName:模板简短名称,必填
    • tags:模板标签
    • sourceName:指定一个字符串,当使用 dotnet new 带 -n 参数时,-n 参数的值会替换 sourceName 指定的字符串。
    • preferNameDirectory:是否生成相同名称的目录,可选。
  3. 1
    dotnet new -i <PATH>   // 当前目录下:dotnet new -i .\

    DemoService 模板安装

从模板创建项目

模板安装成功后,我们可以通过 dotnet new 创建新项目,在存放新项目的目录下执行如下命令:

1
dotnet new swa -n UserService

swaDemoServiceshortName-n 后的 UserService 将替换 DemoService 名,这样一条命令 UserService 服务的基础架子就好了。

UserService
如果对你有帮助就好

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK