{ "author": "Catcher Wong", //others... "symbols":{ //是否启用RequestLog这个Middleware "EnableRequestLog": { "type": "parameter", //它是参数 "dataType":"bool", //bool类型的参数 "defaultValue": "false" //默认是不启用 } }, "sources": [ { "modifiers": [ { "condition": "(!EnableRequestLog)", //条件,由EnableRequestLog参数决定 "exclude": [ //排除下面的文件 "src/TplDemo/Middlewares/RequestLogMiddleware.cs", "src/TplDemo/Middlewares/RequestLogServiceCollectionExtensions.cs" ] } ] } ] }
第二步,在模板的代码中做一下处理
主要是Startup.cs,因为Middleware就是在这里启用的。
using System; //other using... using TplDemo.Core; #if (EnableRequestLog) using TplDemo.Middlewares; #endif /// <summary> /// /// </summary> 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?}"); }); } }
这样的话,只要EnableRequestLog是true,那么就可以包含这两段代码了。
下面更新一下已经安装的模板。
这个时候再去看它的帮助信息,已经可以看到我们加的参数了。
下面先建一个默认的(不启用RequestLog)
dotnet new tpl -n NoLog
这个命令等价于
dotnet new tpl -n WithLog -E false
下面是建好之后的目录结构和Startup.cs
可以看到RequestLog相关的东西都已经不见了。
再建一个启用RequestLog的,看看是不是真的起作用了。
dotnet new tpl -n WithLog -E true
可以看到,效果已经出来了。
下面在介绍一个比较有用的特性。动态切换,这个其实和上面介绍的内容相似。
动态切换
直接举个例子来说明吧。
假设我们的模板支持MSSQL, MySQL, PgSQL和SQLite四种数据库操作
在新建一个项目的时候,只需要其中一种,好比说要建一个PgSQL的,肯定就不想看到其他三种。
这里不想看到,有两个地方,一个是nuget包的引用,一个是代码。
上一小节是对某个具体的功能进行了开关的操作,这里有了4个,我们要怎么处理呢?
我们可以用类型是choice的参数来完成这个操作。
修改template.json,加入下面的内容
{ "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\")" } } }
看了上面的JSON内容之后,相信大家也知道个所以然了。有一个名为sqlType的参数,它有几中数据库选择,默认是MsSQL。
还另外定义了几个计算型的参数,它的取值是和sqlType的值息息相关的。
MsSQL,MySQL,PgSQL和SQLite这4个参数也是我们在代码里要用到的!!
修改csproj文件,让它可以根据sqlType来动态引用nuget包,我们加入下面的内容