-
-
Save explorer14/e3d5f76c8180cdb5bcecba55f1556aa8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Generator] | |
public class DtoGenerator : ISourceGenerator | |
{ | |
public void Execute(GeneratorExecutionContext context) | |
{ | |
var targetTypeTracker = context.SyntaxContextReceiver as TargetTypeTracker; | |
var codeBuilder = new StringBuilder(); | |
foreach (var typeNode in targetTypeTracker.TypesNeedingDtoGening) | |
{ | |
var generatedDtoClassName = $"{typeNode.Identifier.ValueText}Dto"; | |
// emit code to create the DTO class with property getters and setters | |
// ... | |
// Start emitting mapping extension methods | |
codeBuilder.AppendLine($"\tpublic static class EntityExtensions{Guid.NewGuid().ToString().Replace("-", string.Empty)}"); | |
codeBuilder.AppendLine("\t{"); | |
codeBuilder.AppendLine($"\t\tpublic static {generatedDtoClassName} ToDto(this {typeNode.Identifier.ValueText} entity)"); | |
codeBuilder.AppendLine("\t\t{"); | |
codeBuilder.AppendLine($"\t\t\t\treturn new {generatedDtoClassName}"); | |
codeBuilder.AppendLine($"\t\t\t\t{{"); | |
foreach (var pds in allProperties) | |
{ | |
var symbol = context.Compilation | |
.GetSemanticModel(pds.SyntaxTree) | |
.GetDeclaredSymbol(pds); | |
var property = (symbol as IPropertySymbol); | |
codeBuilder.AppendLine($"\t\t\t\t\t{property.Name} = entity.{property.Name},"); | |
} | |
codeBuilder.AppendLine($"\t\t\t\t}};"); | |
codeBuilder.AppendLine("\t\t}"); | |
codeBuilder.AppendLine("\t}"); | |
codeBuilder.AppendLine("}"); | |
context.AddSource(generatedDtoClassName, | |
SourceText.From(codeBuilder.ToString(), Encoding.UTF8)); | |
codeBuilder.Clear(); | |
} | |
} | |
public void Initialize(GeneratorInitializationContext context) => | |
context.RegisterForSyntaxNotifications(() => new TargetTypeTracker()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment