Using C# Source Generators to Generate Data Transfer Objects (DTOs)
Tags: csharp, sourcegenerators, automation, developerproductivity
Published: 2021-07-29 05:24:39

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">For many enterprise applications, there would normally be a split between domain entities that live inside the application core and DTOs that are exposed to the outside world, for e.g. as outgoing data structures from a web service. Often these structures are symmetric to domain entities, i.e. they contain all of the same properties that domain entities contain but <em>most likely</em> none of the logic. There are 2 problems with this pattern however:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>This tends to be a very manual and time consuming task that doesn't add much value</li><li>The code you have to write to map from the domain entities to these DTOs  tends to be repetitive and error prone. Mistakes can often occur leading to broken contracts with the consumers of the DTO. </li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Using C# Source Generators to generate DTOs could <em>potentially</em> save a lot of developer time, so in this post I am going to attempt to write just such a generator.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>DISCLAIMERS</strong>: </p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>This may not be the most performant way or the most sensible to write source generators so if you know of a better way, please by all means comment away!</li><li>The code shown here will very likely be very hard to follow at times especially in the last half of part 2, its OK if you don't follow all of it. You are writing code within code essentially, so it <strong>is</strong> a bit messy by design. I will put the fully refactored code on Github with a readme that describes some of the Roslyn APIs so that should help a little.</li><li>The whole thing is a bit of an experiment, I've not used this code in any production application yet. I intend to at some point to get some real feedback on its viability but nothing as yet. For now I am really curious to see what's possible and how far I am willing to and/or comfortable, pushing it.</li><li>Implementation is a bit opinionated so it will not cater for all edge cases.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong>ASSUMPTIONS</strong>:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>No inheritance relationship between domain entity classes. All entity classes are therefore assumed to be at the same level of hierarchy.</li><li>Either the whole entity class will be mapped to a DTO or not at all, excluding properties from being mapped whilst possible is not in the current scope.</li><li>DTOs are assumed to be outgoing from, say a web service or a REST API so persistence related models are out of scope for now because they might require additional data access related code to be added to the DTOs for e.g. special attributes specific to ORMs, access modifiers etc which for a generic code generator is too much responsibility and will make things too complicated. </li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>What is source generation? </h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">At its most basic, source generation is basically what it sounds like: auto-generated code. There are two main types: <em>compile time</em> and <em>post-compilation or IL emitting</em>. Former ties into the existing build toolchain and the latter is a bit more challenging because you need to know IL and emitting correct IL is hard if not impossible. I could imagine both being relatively difficult to test using conventional testing techniques. Usually a lot of trial and error might be involved and there might often be limited support for debugging. Source generation is not a new concept, its been around for a long time in the form of tools like T4, Postsharp, Fody etc but I have never used these tools in the past...well...except for may be T4 several years ago...once.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">C# Source Generators allow emitting C# code during the compilation process and include the emitted code in the rest of build process such that it builds along with the rest of your code. The compiler passes the control to the <code>ISourceGenerator</code> implementation to add code to the syntax tree and the emitted code is then included in the rest of compilation process as normal. This <a rel="noreferrer noopener" href="https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/" target="_blank">blog post</a> goes into a lot of the "whats" and the "whys" so I am not going to.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Compiler 101</h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">The C# compiler creates two models from the code you write: <em>syntactic</em> <em>model</em> i.e. how is the code structured in terms of tokens for e.g. starts with access modifier, then return type then identifier then parenthesis etc basically your cs file and <em>semantic</em> <em>model</em> i.e. what does the code mean for e.g. what is a property? what are the type arguments for a generic type? etc. During the compilation process, the parser parses the code into a syntax tree and generates the semantic model for this tree, these  two models are then passed to your source generator to scan, and emit code based on criteria you define. For e.g. generate DTOs for all entity classes decorated with a certain attribute.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Generating DTOs from Basic Domain Entities (only primitive types)</h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">First things first, I will add a console app (call it <code>ConsoleApp9</code>) to a new solution where I can define my domain entities, and later will reference the source generator to do some code generation.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">For this blog post I will create a basic <code>Employee</code> domain entity that looks like this:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/29b37f1bc9ffd5c7f2b569bfe29e555d %}

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">The corresponding DTOs might look something like this - basically just open property bags:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/d128b1d12ecd3b83ec626921d77fd50b %}

<!-- wp:heading -->
<h2>How do I get from the domain to DTO ?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">The next thing I've got to do is create a new .NET Standard 2.0 class library project in my solution that I created earlier. This library project can then be shipped as a Nuget package later. <strong>NOTE</strong>: I do need all those <em>Microsoft.CodeAnalysis.*</em> packages to create a source generator. The C# language version has to be <code>latest</code> and in order to see what files the compiler outputs, I'll set the <code>EmitCompilerGeneratedFiles</code> attribute to <code>true</code> and specify a folder for the generated files to go into (last two lines in the following csproj snippet).</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/5924838598648460ebebb7f04c39e6e3 %}

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Now I need to create an implementation of the <code>ISourceGenerator</code> interface in this project and decorate it with <code>Generator</code> attribute for the compilation process to pick it up as a source generator.</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/1129228a984f875713e3a7854e2e464a %}

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">What I want to do in order to help the source generator find the types that need converting to DTO, is decorate my domain types with a  custom attribute which I will create in the source generator project:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/bfed2088b256750596d84671cace554d %}

<!-- wp:paragraph -->
<p>and then tack it on the my domain entities that I want DTOs for:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/8db92b0abd89957c8178bb100e67b01c %}

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">In order to tell my source generator which classes to generate code for, I need to also implement <code>ISyntaxContextReciever</code> and register it with the source generator (in the <code>Initialise()</code> method). This receiver is kind of a hook that the compiler calls into as it traverses the syntax tree node by node:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/4a1c283a6c39d4e297ee83c36c1bdca7 %}

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">During each visit, I will check to see if the <code>TypeDeclarationSyntax</code> node (for e.g. a class or a struct) is decorated with the <code>GenerateMappedDto</code> attribute and if it is, I will simply add it to a list. That done its time to register this receiver with the source generator:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/c7769c844117da75617cf841a988ca97 %}

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify"><code>TypeDeclarationSyntax</code> is the base type for the <code>ClassDeclarationSyntax</code> and <code>StructDeclarationSyntax</code> so will cover both container types and will allow generating DTOs for both. Once the entire syntax tree is thus visited, the control will be transferred back to the source generator and the compiler will pass it both the syntactic model and the semantic model using which I can write out the <em>actual</em> code:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/c4e75cd2d3dcd7f24092b74164504554 %}

<!-- wp:paragraph -->
<p>There is a quite bit going on here so I will unpack, I am using the semantic model for the most part because that gives me richer set of information about the code:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>I'd also like, for simplicity reasons, to put the DTOs in "Dtos" namespace under the main domain namespace. So if the entity is in <code>MyApp.Domain</code> then the dtos will be in <code>MyApp.Domain.Dtos</code> (<em>Line 17</em>)</li><li>I will like the DTOs to have a naming convention of "{Entity class name}Dto". For e.g. <code>Employe</code> entity class will have a DTO class named <code>EmployeeDto</code>. (<em>Line 2</em>0)</li><li>I am importing some generic framework libraries. Nothing fancy about that (<em>Lines 23-25</em>)</li><li>Then goes the meat of the class body (<em>Lines 32-41</em>) (more on this in a sec!)</li><li>Close class and namespace definitions.</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>So what's the meat here?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Essentially, each property in the DTO will be mapped to the corresponding property in the domain entity, with the same name and type. So I am looping over all the <code>PropertyDeclarationSyntax</code> nodes in the domain entity syntax model and emitting corresponding properties. In the <code>BuildDtoProperty()</code> method, I am once again using the semantic model to get more information about the property type which is available via <code>property.Type</code> <em>property</em>. Then I've just added a simple extension method to get the condensed name of the type for e.g. <code>Guid</code> instead of <code>System.Guid</code> (just personal readability preference).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It literally emits: <code>public Guid Id {get;set;}</code></p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>BTW, all these various syntax/symbol classes are a part of the Roslyn C# syntax API that you can browse <a rel="noreferrer noopener" href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.csharp.syntax?view=roslyn-dotnet-3.9.0" target="_blank">here</a>.</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>That...is basically it for a very minimal (<em>read: limitedly useful</em>) DTO generator!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>How do I actually use this generator in my application?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Remember our <code>ConsoleApp9</code> that we added earlier? I will now add to it a <strong>project reference </strong>to the source generator project:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/explorer14/c6968a2f5e9233de31e89368b1a3e491 %}

<!-- wp:paragraph -->
<p>Two things of note here: </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>1) I have added the <code>GenerateMappedDtoAttribute</code> class as a linked file temporarily, eventually this would be a part of the Nuget package so the linked file reference can be removed from the <code>ConsoleApp9.csproj</code>, and </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>2) the project reference doesn't reference the output assembly and also sets the item type to <code>Analyzer</code>. The former will make sure that any transitive dependencies of the source generator project don't get added as references of the console app project itself (<em>this attribute is not needed when adding a <code>PackageReference</code></em>) and the latter will make it appear as an analyzer under dependencies and this is also where I can see the generated DTO.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":5142,"sizeSlug":"large","linkDestination":"media"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><a href="https://codequirksnrants.files.wordpress.com/2021/07/image.png"><img src="https://codequirksnrants.files.wordpress.com/2021/07/image.png?w=468" alt="" class="wp-image-5142"/></a></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Now I am all set to generate my very first DTO automagically! I'll just hit Ctrl+Shift+B in Visual Studio (or do <code>dotnet build</code> from the CLI), to build the solution! If you are doing this for the first time you might notice that nothing seems to have changed in <code>ConsoleApp9</code>! 🤔No DTOs in sight, nothing and if you are unlucky there might be some build errors to boot as well, what's that about? </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Well, this is where we might want to pay heed to the <a rel="noreferrer noopener" href="https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/#why-do-i-not-get-intellisense-for-generated-code-why-does-visual-studio-say-theres-an-error-even-though-it-builds" target="_blank">recommendation</a> of source generator creators:</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>You will need to restart Visual Studio after building the source generator to make errors go away and IntelliSense appear for generated source code. After you do that, things will work. Currently, Visual Studio integration is very early on. This current behavior will change in the future so that you don’t need to restart Visual Studio.</p><cite>- Microsoft</cite></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">I don't think VS Code suffers from this issue and I haven't tried this on Rider, unfortunately, my trial expired before I embarked on source generators so that mystery will stay a mystery for now!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Once I do the proverbial "turn it off and on again", I now see the DTO light up in the consuming project and intellisense should also pick it up. Now bear in mind, these generated DTOs don't get checked into source control because..well..they get generated at build time!😁But they <strong>will</strong> get packaged into my application binaries during deployment, so I can rest easy!</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":5145,"sizeSlug":"large","linkDestination":"media"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><a href="https://codequirksnrants.files.wordpress.com/2021/07/image-1.png"><img src="https://codequirksnrants.files.wordpress.com/2021/07/image-1.png?w=494" alt="" class="wp-image-5145"/></a></figure></div>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>How do I Nuget-ify my source generators?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>For this I will modify the csproj of the source generator to:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>Add a package version (come on, we're not animals!)</li><li>Instruct the <code>dotnet pack</code> command to put the analyser in a pre-designated folder in the generated nuget package (<em>I ended up spending several frustrating minutes trying to figure out why the analyser was not showing up in my consuming project, this turned out to the missing piece! Now you know as well!</em>)</li></ol>
<!-- /wp:list -->

{% gist https://gist.github.com/explorer14/237d462390274c6cf280b82f98862734 %}

<!-- wp:paragraph {"align":"justify"} -->
<p class="has-text-align-justify">Once this package is pushed to nuget feed, I can replace <code>ProjectReference</code> with <code>PackageReference</code> in my <code>ConsoleApp9</code> project, remove the <code>ReferenceOutputAssembly</code> attribute from it and I'm off to the races! Now whenever I add a new property to my domain entity, all I have to do now is build the project and the DTO will be automatically updated. That's a lot of developer time saved potentially!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>What's missing?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As cool as this was, the generator is very basic in that it doesn't support:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Properties with complex types for e.g. Employee class having a <code>Address</code> type property which in turn could be composed of primitive types.</li><li>Properties with generic types with one or more primitive type arguments for e.g. <code>Employee</code> class having an <code>IReadOnlyCollection&lt;string&gt;</code> property called Dogs (<em>may be for some godforsaken reason we want to track the names of their dogs! I know you pooped on the carpet, Winston!</em> 🤷‍♂️)</li><li>Properties with generic types with one or more complex type arguments for e.g. <code>Employee</code> class having a <code>IReadOnlyCollection&lt;CompanyAsset&gt;</code> called AssetsAllocated or some completely made up property of type <code>Dictionary&lt;int,Spaceship&gt;</code>, and</li><li>Generating mapping extension methods to convert entities to DTOs. This could potentially be a bigger win in terms of time saving!</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>These I will cover in the final part of this blog post!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><em>Header image <a href="https://www.henkla.se/deep-dive-into-c-9/" target="_blank" rel="noreferrer noopener">source</a></em></p>
<!-- /wp:paragraph -->

Checkout part 2 [here](https://dev.to/coolblue/using-c-source-generators-to-generate-data-transfer-objects-dtos-part-2-4536)