7

我正在尝试为 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 进行哪些更改才能获取我的自定义类?

复制:Github

4

1 回答 1

5

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

几乎一切都是正确的,除了自定义代码生成器不能与 Web 项目驻留在同一个程序集中,并且自定义代码生成器应该作为包引用从 Web 项目中引用(项目引用不起作用)。

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

  • 应该在 web 项目之外
  • 应该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

请参阅此处的相关讨论

于 2016-12-30T23:33:34.047 回答