jjk*_*les 7 c# code-generation asp.net-core dotnet-cli
我正在尝试为 dotnet core 编写一个自定义代码生成器,但到目前为止几乎没有成功,因为它周围的文档有限。
仔细研究了 CodeGeneration 源代码,了解了如何从命令行触发生成器以及它的内部工作原理。
由于 dotnet core 中可用的生成器不能满足我的需求,我尝试编写自己的 CodeGenerator,但似乎无法通过“dotnet aspnet-codegenerator”命令调用它。下面是我的自定义代码生成器(目前没有实现 - 我的目标是能够从 dotnet cli 触发它并以异常结束),
namespace TestWebApp.CodeGenerator
{
[Alias("test")]
public class TestCodeGenerator : ICodeGenerator
{
public async Task GenerateCode(TestCodeGeneratorModel model)
{
await Task.CompletedTask;
throw new NotImplementedException();
}
}
public class TestCodeGeneratorModel
{
[Option(Name = "controllerName", ShortName = "name", Description = "Name of the controller")]
public string ControllerName { get; set; }
[Option(Name = "readWriteActions", ShortName = "actions", Description = "Specify this switch to generate Controller with read/write actions when a Model class is not used")]
public bool GenerateReadWriteActions { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我尝试调用代码生成器的方式,
dotnet aspnet-codegenerator -p . TestCodeGenerator TestController -m TestWebApp.Models.TestModel
Run Code Online (Sandbox Code Playgroud)
或者
dotnet aspnet-codegenerator -p . test TestController -m TestWebApp.Models.TestModel
Run Code Online (Sandbox Code Playgroud)
但是,这似乎不起作用,并抱怨无法找到自定义代码生成器。请参阅下面的错误消息,
Finding the generator 'TestCodeGenerator'...
No code generators found with the name 'TestCodeGenerator'
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGeneratorsLocator.GetCodeGenerator(String codeGeneratorName)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
RunTime 00:00:06.23
Run Code Online (Sandbox Code Playgroud)
我遗漏了什么或者我应该为 CogeGenerator 做哪些改变来获取我的自定义类?
复制:Github
好的。发现我的代码中缺少什么。
几乎一切都是正确的,除了自定义代码生成器不能驻留在与 Web 项目相同的程序集中,并且自定义代码生成器应该从 Web 项目中引用为包引用(项目引用不起作用)。
以下是 dotnet cli 代码生成器可见的自定义代码生成器的要求,
Microsoft.VisualStudio.Web.CodeGeneration
作为依赖dotnet pack -o ../custompackages
(确保将此位置(../custompackages)添加到 nuget.config 中)
注意:我的问题中的代码有一个不接受模型参数(-m 开关)并需要一个controllerName 参数的模型,因此,要调用您必须使用的代码生成器,
dotnet aspnet-codegenerator -p . test --controllerName TestController
Run Code Online (Sandbox Code Playgroud)
或者
dotnet aspnet-codegenerator -p . TestCodeGenerator --controllerName TestController
Run Code Online (Sandbox Code Playgroud)
请参阅此处的相关讨论
归档时间: |
|
查看次数: |
5509 次 |
最近记录: |