JsonSrcGen + CoreRT = Pure Magic
In my previous post I talked about how using a Source Generator allows us to make a reflection free Json generator. This has serious advantages when it comes deployment size and startup time.
These advantages become even bigger when paired with an AOT or Ahead Of Time compiler like CoreRT. CoreRT can produce impressively small binaries but cannot do Reflection.Emit and has only limited support for reflection. But seeing as JsonSrcGen doesn't do any reflection the two are a match made in heaven.
For me this produces a binary that is only 2.1 MB and will startup and serialise a simple Json class in only 5 ms.
In order to see just how good this is here a comparison to what you can do with the officially supported .NET Json and self contained publishing options. Which included the new Trimming and Ready To Run options.
How to use JsonSrcGen with CoreRT
1. Create a new .NET 5 console project
2. Add the CoreRT Package Source
CoreRT requires a custom package source to be added to your nuget.config. I didn't have one so added one using:
Then add the dotnet-core Package Source to your nuget config so it looks as follows:
3. Add the CoreRT and JsonSrcGen nuget packages
4. Add the following lines to you .csproj file
The first line is required because Source Generators are currently in preview, this will not be required once they are released.
The Second line tells CoreRT that we do not need reflection, this is a significant saving in binary size.
The final line tells CoreRT that we do not need localisation support.
5. Install prerequisites
What you need here depends on your platform, but for me on linux I needed the following:
6. Then build the project to get your output
The -r linux-x64 tells CoreRT to build for linux 64 bit, if you are on a different platform you will need to change this.
7. If you are on linux use the strip command to get rid of debug information
This step is only required on linux, because the debug information ends up in the binary on linux.
Please checkout the JsonSrcGen project on github: https://github.com/trampster/JsonSrcGen
You can find a JsonSrcGen CoreRT sample project in our samples folder