AutoActions for Skinny controllers–custom template
Now I want to let the user make his own template. For this, I have enriched the attribute AutoActionsAttribute with a
public string CustomTemplateFileName { get; set; }
The code was pretty easy, just reading from GeneratorExecutionContext . AdditionalFiles instead of reading from the template in the dll
switch (templateId) { case TemplateIndicator.None: context.ReportDiagnostic(DoDiagnostic(DiagnosticSeverity.Info, $"class {myController.Name} has no template ")); continue; case TemplateIndicator.CustomTemplateFile: var file = context.AdditionalFiles.FirstOrDefault(it => it.Path.EndsWith(templateCustom)); if (file == null) { context.ReportDiagnostic(DoDiagnostic(DiagnosticSeverity.Error, $"cannot find {templateCustom} for {myController.Name} . Did you put in AdditionalFiles in csproj ?")); continue; } post = file.GetText().ToString(); break; default: using (var stream = executing.GetManifestResourceStream($"SkinnyControllersGenerator.templates.{templateId}.txt")) { using var reader = new StreamReader(stream); post = reader.ReadToEnd(); } break; }
There are 2 small catches
1 see the EndsWith ? The GeneratorExecutionContext . AdditionalFiles gives you the full path
2. the additional files should be registered in the .csproj
<ItemGroup>
<AdditionalFiles Include=”Controllers\CustomTemplate1.txt” />
</ItemGroup>
Now the user can define his own template for the controller like this
[AutoActions(template = TemplateIndicator.CustomTemplateFile, FieldsName = new[] { "*" } ,CustomTemplateFileName = "Controllers\\CustomTemplate1.txt")] [Route("api/[controller]/[action]")] [ApiController] public partial class CustomTemplateController : ControllerBase { private readonly RepositoryWF repository; public CustomTemplateController () { //do via DI repository = new RepositoryWF(); } }
And this is all ! ( ok. some documentation should be involved)
Leave a Reply