gpt4 book ai didi

c# - 为 Dotnet Core 编写自定义代码生成器

转载 作者:行者123 更新时间:2023-11-30 21:43:51 24 4
gpt4 key购买 nike

我正在尝试为 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; }
}
}

下面是我尝试调用代码生成器的方式,

dotnet aspnet-codegenerator -p . TestCodeGenerator TestController -m TestWebApp.Models.TestModel

dotnet aspnet-codegenerator -p . test TestController -m TestWebApp.Models.TestModel

不过,这似乎不起作用,并提示无法找到自定义代码生成器。请参阅下面的错误消息,

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

我缺少什么或者我应该做哪些更改才能让 CogeGenerator 接收我的自定义类(class)?

复制:Github

最佳答案

好的。找出我的代码中缺少的内容。

几乎所有内容都是正确的,除了自定义代码生成器不能与 Web 项目驻留在同一程序集中这一事实外,自定义代码生成器应该作为包引用从 Web 项目中引用(项目引用将不起作用).

以下是自定义代码生成器对 dotnet cli 代码生成器可见的要求,

  • 应该在网络项目之外
  • 应该有 Microsoft.VisualStudio.Web.CodeGeneration 作为依赖
  • 应将自定义代码生成器打包并添加为将使用代码生成器的 Web 项目的依赖项

dotnet pack -o ../custompackages

(确保将此位置 (../custompackages) 添加到 nuget.config)

注意:我问题中的代码有一个不接受 Model 参数(-m 开关)并需要 controllerName 参数的模型,因此,要调用您必须使用的代码生成器,

dotnet aspnet-codegenerator -p . test --controllerName TestController

dotnet aspnet-codegenerator -p . TestCodeGenerator --controllerName TestController

引用相关讨论here

关于c# - 为 Dotnet Core 编写自定义代码生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com