Skip to content

Instantly share code, notes, and snippets.

@explorer14
Last active July 17, 2021 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save explorer14/e3d5f76c8180cdb5bcecba55f1556aa8 to your computer and use it in GitHub Desktop.
Save explorer14/e3d5f76c8180cdb5bcecba55f1556aa8 to your computer and use it in GitHub Desktop.
[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