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

时间:2016-12-27 22:28:41

标签: c# asp.net-core code-generation dotnet-cli

我正在尝试为dotnet核心编写自定义代码生成器,但到目前为止,围绕它的文档有限,几乎没有成功。

稍微探讨CodeGeneration源代码,了解如何从命令行触发生成器以及它如何在内部工作。

由于dotnet核心中可用的生成器不足以满足我的需求,我尝试编写自己的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为我的自定义课程做些什么改变?

Repro:Github

1 个答案:

答案 0 :(得分:3)

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

几乎所有内容都是正确的,除了自定义代码生成器不能与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

OR

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

参考相关讨论here

相关问题