- Documentation and samples
- Source Generators
- Meta - libs and generators for other generators
- Tips & Tricks
- Articles
- Videos
- Demo, PoC and excercise projects
- Projects using custom Source Generators "internally"
A list of C# Source Generators (not necessarily awesome), because I haven't found a good list yet.
C# Source Generators is a Roslyn compiler feature introduced in C#9/.NET 5. It lets C# developers inspect user code and generate new C# source files that can be added to a compilation.
Add GitHub topic csharp-sourcegenerator
to your generator repo - let's get it started!
- docs.microsoft.com official documentation.
- dotnet/roslyn feature design document describing the compiler feature.
- dotnet/roslyn cookbook to help with generator creation.
- dotnet/roslyn-sdk samples show how to implement a source generator and use features like external package references (inside generators). Includes AutoNotify, Csv, Maths, Mustache, and SettingsXml.
- SourceGeneratorPlayground - an online Source Generator Playground to play with generator ideas ๐ก without any setup noise. Source repo.
- davidwengier/SourceGeneratorTemplate - A basic template for writing a C# source generator, from the Roslyn dev.
- AdaskoTheBeAsT.Identity.Dapper - - Custom Dapper implementation for Microsoft.Extensions.Identity.Stores (part of ASP.NET Core Identity)
- AjaxService.Gen - - Automatically Generate typescript Ajax calls based on your C# Api endpoints.
- AnyOf - The Source Generator creates a
AnyOf<First, TSecond, ...>
type to handle multiple defined types as input parameters for methods. - ApiClientGenerator - Generates a strongly typed HttpClient based off MVC's default routing. Can be used to output into multiple projects, like Blazor WebAssembly.
- Architect.DomainModeling - A complete Domain-Driven Design (DDD) toolset for implementing domain models, including base types and source generators for ValueObjects, WrapperValueObjects, Entities, and Identities.
- AutoCtor - AutoCtor is a Roslyn Source Generator that will automatically create a constructor for your class for use with constructor Dependency Injection.
- AutoDeconstructable - Generator for efficient and automatic flat text serializer/deserializer using Deconstructable aspect in NTP library.
- AutoDto - - A source generator that generates DTO models from BL to avoid same BL and DTO models
- AutoFilterer.Generators - AutoFilterer.Generators aims to generate filter DTOs from entities automatically via using dotnet source generators.
- AutoInterface - interface-to-member source generator.
- AutoInvoke - A generator that generates a method that invokes a specified generic method, for every Type in your project that satisfies a defined constraint.
- AutoRegisterInject - Automatically generate Microsoft Dependency Injection ServiceCollection registrations for your classes from attributes.
- AutoSpectre - Generates a service for prompting and populating a class using the Spectre.Console library
- Avalonia.NameGenerator - Generates typed references to named Avalonia XAML controls.
- avatar - A modern compile-time generated interception/proxy library.
- Azura - Generates binary [de]serializers on Streams at design time.
- BetterEnums - C# Enums with values and better performance as a source generator
- BigMachines - BigMachines is State Machine library for .NET.
- BlazorInteropGenerator - Generates Blazor -> Javascript strongly typed interop methods, by parsing the Javascript it self and generating extension methods for IJSRuntime.
- BlazorOcticons - Github Octicons created as a
.razor
components using source generator. The generated components are available via the NuGet package, the generator itself is available as a separate NuGet package. The project website is an example using the generated components. - boilerplatezero - WPF Dependency Property and Routed Event generator.
- Breezy - Micro ORM with source generator.
- Buildenator - Generate data builder classes for testing purposes (and not only) for your entities. Autofixture + Moq extensions.
- Cloneable - auto-generate Clone method.
- ComputeSharp - A .NET library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders, which are transpiled from C# and precompiled at build-time using source generators.
- ControllerGenerator - Automatically generate controllers from services in a web application
- CoreWCF - CoreWCF provides support of WCF server side code on .NET Core / .NET6. CoreWCF allows users to inject services into
OperationContract
implementation using a source generator to provide anOperationContract
implementation that fits the expectedServiceContract
. The supplied implementation fetch services from the DI container the same way the[FromServices]
attribute works in ASP.NET core MVC Controllers. The source generator supports both a dedicated[Injected]
attribute and the ASP.NET Core MVC[FromServices]
attribute. - Credfeto.Enumeration.Source.Generation - Enum to text generator for enums - generates strongly typed enums for all enums in the assembly, and using
EnumText
attribute for third party enums. Also includes an analyzer to ensure that all enum usages use the.GetName
extension method rather than.ToString
. - CSV-Parser-Generator - A Parser for CSV with support for uncommon line separators (e.g. Unicode) and instantiation of read-only objects and working nullable handling.
- Data Builder Generator - Generate data builder patterns for your model classes.
- DependencyManagement - The Dependency Management is a very fast dependency injection and components container, with many interesting features, and without reflection.
- DependencyPropertyGenerator - Dependency property and routed event source generator for WPF/UWP/WinUI/Uno/Avalonia/MAUI platforms.
- DevExpress.Mvvm.CodeGenerators - Generates boilerplate code for your View Models (INotifyPropertyChanged, Commands, IDataErrorInfo, DevExpress services). Compatible with the Prism and MVVM Light libraries.
- docopt.net - generates C# source code that parses command-line arguments into a strong-typed arguments class (also generated), given just the POSIX-style usage in plain text as part of the CLI. In other words, write the help message for your program and get the entire parser generated for free!
- dot-env-generator - A source generator for C# that turns
.env
files into runtime constants. - dotVariant - A type-safe and space-efficient sum type for C# (comparable to discriminated unions in C or C++).
- DumplingsDevs.Pipelines - The most flexible mediation implementation in the .NET ecosystem with your own types.
- DudNet - A C# source generator for implementing a proxy pattern.
- Dunet - A simple source generator for discriminated unions in C#.
- Durian - Extends the default capabilities of C# by mimicking features from other languages.
- Enum.Source.Generator - A C# source generator to create an enumeration (enum) class from an enum type. With this package, you can work on enums very, very fast without using reflection.
- EnumClass - Generate Kotlin's
enum class
from C#enum
with additional features like Switch function (instead ofswitch
statement). It also contains support libraries like generator for JsonConverter for generated classes - EnumerationClassGenerator - - A C# source generator to create an enumeration class from an enum type.
- EnumFastToStringDotNet - - Automatically generates enum extension methods that implement a switch expression based ToString method.
- EnumUtilitiesGenerator - - A source generator to generate compile-time mapping of enums and description attributes.
- Fairy - generates C# code based on Sitecore Content Serialization (SCS)
.yml
files. - FastEnumGenerator - An enum like generator where you create a partial class with private enum and it will generate an enum like record struct even including returning the words and a list.
- FastGenericNew - The ultimate fast alternative to
Activator.CreateInstance<T>
/new T()
. Built on SourceGenerator V2 (Incremental Generator). - Figgle - - Generate ASCII banner text at compile time (or run time) using figlet fonts.
- Flattening - - C# source generator for generating flattened classes from complex domain classes.
- FluentAssertions.Eventual - - Generates a specialized waiting wrapper for
FluentAssertions
assertions, offering a syntax similar to plainFluentAssertions
. - FluentBuilder - - A project which uses Source Generation to create a FluentBuilder for a specified model or DTO.
- GeneratedJsonConverters - - generate json converters for polymorph contracts and string based enum serialization.
- GenerateHelperLibraries - A source generator where you can send any code to the client without having to do as a string. Helper for custom classes a client has to override in order to have additional features for source generators. Intended to be used from another source generator.
- Generator.Equals - generates equality and hashing for classes and records, supports a number of strategies for comparing collections and properties.
- GitBuildInfo.SourceGenerator - - for dumping the git information (commit hash, branch, the head description) into assembly level metadata attributes.
- Gobie - - Allows developers define and use custom source generation without writing any generator code themselves or learning the Roslyn APIs. Instead, devs define the generator they want, in C#, and can then use that generator throughout their project.
- GraphQL.Tools - - A GraphQL to C# compiler (code-generator) which turns your GraphQL schema into a set of C# classes, interfaces, and enums.
- GrpcInjection - - GrpcInjection is a tool that allow you to inject Services and Interceptor in time of compilation inside of GRPC Projects using C# source generator.
- GRPC-Mock-Server - - A source generator for stubbing GRPC services.
- HttpClientCodeGenerator - - HttpClientGenerator is a tool that uses the Roslyn code generator feature to write boilerplate HttpClient code for you.
- H.NSwag.Generator - - C# Source Generator for NSwag.
- IDisposableGenerator - - a Source Generator for Generating the Dispose functions in Disposables. All you have to do is mark them with attributes and it will work from there.
- Immutype - - generates extension methods to support immutability.
- Imp.NET - - a fast, high-level, object-oriented C# networking library that supports the invocation of remote methods through proxy interface objects.
- Injectio - - Source generator that helps register discovered services in the dependency injection container
- InterfaceGenerator - - Auto generate interface definition by implementation, for when you need an abstraction for the sake of mocking.
- IoTHubClientGenerator - Build a C# Azure IoT Device client program in seconds!
- Jab - - Compile Time Dependency Injection
- JOS.Enumeration - Enumeration class powered by source generation
- JsonByExampleGenerator - - generate classes based on example json files in your project.
- JsonDeserializeResourceSourceGenerator - Instead of having to do embedded resource, can instead have json as additional file and it will produce a c# string and will deserialize to a type specified.
- JsonPolymorphicGenerator - - Source Code Generator for System.Text.Json JsonDerivedType attributes on polymorphic classes
- JsonSerializerContextGenerator - A source generator that produces nearly the same code ahs system.json.text but easier to use because you only have to put an attribute for a model class you want to produce for. Also, produces a method to register to make it easy to use that source generator when serializing/deserializing json.
- JsonSrcGen - - compile time JSON serializer generation.
- kli.Localize - - localize strings from json files via source code generation
- lambdajection - Framework for building AWS Lambdas using dependency injection and aspect-oriented programming.
- Lazysh - Lazy implementation of any interface.
- LinqGen - Alloc-free and fast replacement for Linq, with code generation.
- LoggingDecoratorGenerator - Generates logger decorator class for an interface. Uses Microsoft.Extensions.Logging.ILogger to log and requires it in decorator class constructor.
- Lombok.NET - Generates boilerplate code and common code patterns. As the name suggests, it is the .NET version of Java's Lombok.
- M31.FluentAPI - - Generates fluent APIs for your classes.
- MapDataReader - - Fast mapping
IDataReader
to a custom class - Mapperly - - A source generator for generating object mappings. Inspired by MapStruct.
- MappingCloningExtensions - Generates extensions of objects for mapping and cloning using either attributes or fluent style. Also, supports deep copying and specfiying whether it can do a deep copy and the possibility of doing so safely.
- MapTo - - A convention based object to object mapper similar to Automapper.
- Matryoshki - Metaprogramming framework based on C# source generators. It allows you to define behaviours with adornments and generate decorators for arbitrary types.
- Mediator - - a high performance implementation of Mediator pattern in .NET using source generators.
- MediatR controllers generator - This generator generates controllers and their methods based on your MediatR requests.
- MemberAccessGenerator - generates
GetMember(int)
and/orGetMember(string)
methods that return property value for a given property name or index (e.g. in positional records). - Microsoft MVVM Toolkit - A modular MVVM library with support for source generators to reduce boilrplate and improve performance.
- MiniRazor - Portable Razor compiler & code generator.
- MockableStaticGenerator - A C# source generator to make an interface and a class wrapper to test static/extension methods.
- MockGen - A C# mocking library based on source generators.
- MockSourceGenerator - A C# mocking library that generates mocks at compile-time using a source generator.
- MrMeeseeks.DIE - An unambigous, convenient, flexible and feature rich compile time dependency injection container.
- MrMeeseeks.ResXToViewModelGenerator - Takes ResX files and generates localization ViewModels for a more convenient usage of localization in MVVM projects.
- MrMeeseeks.StaticDelegateGenerator - Makes static classes and members injectable as dependency by generating delegating interfaces and their implementing classes.
- MrMeeseeks.Visitor - Generates the boilerplate code for applications of the Visitor pattern.
- MvvmGen - A lightweight MVVM library for XAML applications that generates your ViewModels with a C# Source Generator.
- N.SourceGenerators.UnionTypes - Discriminated union type source generator.
- Navitski.Crystalized - Generates domain model based on schema files. Generated model supports undo/redo, saving to/loading from SQLite and Json files, precise changes tracking and more.
- net_automatic_interface - .Net Core Source Generator for Automatic Interfaces.
- NextGenMapper - Easy-to-use mapper without configuration.
- Plastic - This project provides encapsulation of things like Domain, Application Rules, Business Rules or Business Logic in Application.
- PolySharp - Provides generated, source-only polyfills for C# language features, to easily use all runtime-agnostic features downlevel.
- PrimaryConstructor - Generate primary constructor from readonly fields.
- PrimitiveStaticDataGenerator - for creating methods that return optimized
ReadOnlySpan<T>
static data from primitive values. - PrintMembersGenerator - helps re-defining C# record's PrintMembers method to force include/exclude certain members.
- PropertyChanged.SourceGenerator - - Powerful INotifyPropertyChanged Source Generator, which generates INPC boilerplate for you as part of your build. Supports features such as automatic and manual dependencies between properties, notifications when specific properties change, and more.
- ProtobufSourceGenerator - - A source generator that generates partial helper classes where member properties are attributed with ProtoMember attribute.
- ProxyInterfaceGenerator - generate an interface and a Proxy class for classes. This makes it possible to wrap external classes which do not have an interface, in a Proxy class which makes it easier to Mock and use DI.
- Pure.DI - - dependency injection for .NET without any IoC/DI containers, frameworks, dependencies, and thus without any performance impact and side-effects.
- QuickConstructor - A reliable and feature-rich source generator that can automatically emit a constructor from the fields and properties of a class. It can also generate null checks based on nullable reference types annotations.
- RazorPageRouteGenerator - Generates methods with parameters for Razor and Blazor pages, so you can navigate without having to guess URLs or parameters.
- ResXGenerator - Generates strongly-typed resource classes for looking up localized strings.
- Ridge - Generates strongly-typed clients for API based on controller definition and internal application details.
- Safe-Routing - Analyses a project's razor pages and MVC controllers, producing strongly-typed representations of those routes as you type
- ScenarioTests - Test your code like you would write a notebook. Simply and effective
- SerdeDn (serde-sn) - is a port of the popular serde.rs Rust serialization/deserialization library to .NET. Basic cases are fully automated using a C# source generator.
- SmallSharp - Create, edit and run multiple C# 9.0 top-level programs in the same project by just selecting the startup program from the start button.
- SmartAnnotations - A library that uses source generators to automatically generate data annotations for your models. It provides a strongly-typed mechanism (fluent like API) to define your annotation rules.
- SourceApi - - API first Open API code generator based on json or yaml definitions. It generates base abstract controllers with docs, routes, that you inherit and implement in your controllers.
- SourceConfig - - Generates configuration POCO objects, lists, dictionaries in AOT based on *.json config files.
- SourceGeneratorQuery - - C# SourceGenerator helper which helps you query your files, and adds LINQ support.
- SourceInject - A source generator that allow you to generate your services for dependencies injection during compile time.
- SourceMapper - A source generator that creates extension methods for cloning and mapping.
- SourceMapper - - generates Mappers code based on attributes used on interfaces or abstract classes. It is inspired by Java MapStruct
- SpreadCheetah - Create Excel files with a C# Source Generator for generating the rows.
- SqlMarshal - Native AOT friendly-performant mini-ORM. Generation of wrappers for accessing SQL using ADO.NET.
- ST.NSwag.ServerSourceGenerator - Generates Web API/ASP.NET Core controllers from a OpenAPI specification.
- StackXML - Stack based zero-allocation XML serializer and deserializer.
- StringLiteralGenerator - for optimizing UTF-8 binaries.
- StrongInject - - compile time dependency injection for .NET.
- Strongly - Easily generate serializable domain value types
- StronglyTypedEmbeddedResources - Generates strongly typed names for Embedded Resources automatically.
- StructPacker - binary serializer that auto-generates C# serialization code to achieve peak runtime performance and efficiency.
- Svg to C# Source Generators - SVGC compiles SVG drawing markup to C# using SkiaSharp as rendering engine. SVGC can be also used as codegen for upcoming C# 9 Source Generator feature.
- SyncMethodGenerator - - Generates a synchronized method from your async code.
- TeuJson - A Reflection-less and Lightweight Json Library using source generator.
- ThisAssembly - Exposes project and assembly level information as constants in the ThisAssembly class.
- Thunderboltloc - One of the very first IoC frameworks for .Net that has no reflection.
- Tinyhand - - Tiny and simple data format/serializer using a source generator.
- ToString - - C# source generator for implementing
ToString
override likerecord
type. - Transplator - A simple C# source generator for text templates.
- TupleOverloadGenerator - - Overload
params
array parameter with tuples avoiding heap allocations. - TxtToListGenerator - A source generator where if you have a text file as additional file and you have a list ordered by return carriages, then it produces either a list of int or a list of string in c#.
- TypedSignalR.Client - C# Source Generator to create strongly typed SignalR clients.
- ValueChangedGenerator - for generating PropertyChanged from inner struct members.
- ValueLink - A C# Library for creating and managing multiple links between objects.
- ValueObjectGenerator - C# source generator is for ValueObjects (ie.Wrapper classes).
- Visor - C#/F# optics library with incremental code generator.
- Vogen - C# source generator and code analyser that generates strongly typed domain identities.
- WinUI-ObservableSettings - - Generate boilerplates to read and write settings in packaged WinUI 3 app.
- WrapperValueObject - - for creating simple value objects wrapping primitive types.
- AttributesSourceGeneratorHelper - A source generator to help another generator by producing attributes. Anything that inherits from Attribute will be sent to the client so you don't have to build strings for attributes.
- CommonSourceGeneratorsHelpers - A generator to create many helpers for source generators to use to make up that its very difficult to reference third party libraries in source generators including extensions and a source code string builder.
- SourceGeneratorUtils - An essential library equipped with utility functions and helpers to aid in writing source files for source generators or for general purposes. Based on the
System.Text.Json
source generator architecture for best-practices. - SourceGenerator.Helper.CopyCode - - A simple Generator that generates a string representation to an annotated Type.
Collection of tips and tricks (simple and brief to fit in Tweet):
Tweeted by @raboof on May 25 2021 at 23:00:
TIL to debug a source generator in VS 16.10: upgrade Microsoft.CodeAnalysis.CSharp to 3.10.*, add
<IsRoslynComponent>true</IsRoslynComponent>
to source generator project, select Roslyn Component for Launch in Project Properties Debug page, choose Target then F5 ๐
Tweeted by @raboof on Nov 16 2020 at 20:57:
See files emitted by #SourceGenerators by adding these properties to your (*.csproj) project file:
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)Generated</CompilerGeneratedFilesOutputPath>
Tweeted by @Chiser99 on Sep 02 2020 at 06:41:
I made a thing: https://github.com/chsienki/Kittitas
If you're building Roslyn Source Generators or Analyzers check it out, it makes debugging them inside the compiler easier. #roslyn #csharp #dotnetcore #sourcegenerators #analyzers
Build failed in WPF projects microsoft/CsWin32#7:
If your build failed in a _wpftmp.csproj file you need to add following property to your (.csproj) project file:
<IncludePackageReferencesDuringMarkupCompilation>true</IncludePackageReferencesDuringMarkupCompilation>and use at least .NET 5.0.102 SDK
Reference local projects or embed NuGet packages to source generator assemblies dotnet/roslyn#47517:
โ Please be aware that this may result in crashes, when another generator or SDK component loads such an assembly with lower version. If you can, please avoid embedding additional DLLs/packages.
You can add a dependency to a source generator in the same solution through three steps:
- Add a
<PackageReference>
, making sure to set bothGeneratePathProperty="true"
andPrivateAssets="all"
- Add a build target to add
<TargetPathWithTargetPlatformMoniker>
elements as part of GetTargetPath, and add all the required dependency assemblies inside this target, making sure to setIncludeRuntimeDependency="false"
- Update
<GetTargetPathDependsOn>
to ensure the target from the previous step is usedYou can see an example of these steps here: https://github.com/dotnet/roslyn-sdk/blob/0313c80ed950ac4f4eef11bb2e1c6d1009b328c4/samples/CSharp/SourceGenerators/SourceGeneratorSamples/SourceGeneratorSamples.csproj#L13-L30
- Series: Creating a source generator (2022-02-01) Complete series about how to create an incremental source generator, using the APIs introduced in .NET 6.
- Mastering at Source Generators (2022-01-15) Generating CRUD controller from DTO model using text template.
- Using C# Source Generators to create an external DSL (2021-01-27) that shows how to implement a simple DSL.
- 4 ways to generate code in C# โ Including Source Generators in .NET 5 (2021-01-19) demonstrates the comparison between Source Generators, T4 template and Reflection, etc.
- .NET 5 Source Generators - MediatR - CQRS - OMG! (2020-12-16) explores how source generators can be used to automatically generate an API for a system using the MediatR library and the CQRS pattern.
- Source Generators in .NET 5 with ReSharper (2020-11-20) introduces source generators and briefly mentions how they are being worked into the ReSharper product.
- Source Generators - real world example (2020-11-09) contains a rich and deep dive into a real world generator with lots of useful tips.
- How to profile C# 9.0 Source Generators (2020-10-10) demonstrates how to profile your source generator using the performance profiling tools built into Visual Studio.
- How to Debug C# 9 Source Code Generators (2020-10-09) contains debugging tips.
- How to generate code using Roslyn source generators in real world scenarios (2020-09-17) rich story of how ThisAssembly generator was written using Scriban templates.
- .NET Blog 'New C# Source Generator Samples' post (2020-08-25) that shows some simple samples.
- .NET Blog 'Introducing C# Source Generators' post (2020-04-29) that announces the feature.
- C# Source Generators - Write code that writes code - David Wengier (2020-11-13) Roslyn dev takes deep dive into the topic.
- .NET Languages and Runtime Community Standup - Source Generators (2020-10-08) shows how Generators work and how they can be tested.
- Channel 9 'Source Generators in C#' (2020-08-12) has Roslyn PMs discussing the feature.
Maybe they can inspire you too!
- RyanAlameddine/SourceGeneratorDemo - contains 3 demos: hello world, INPC and OpCode class.
- TMC-CSharp/CodeExerciseLibrary - Library to help creating C# exercises. Generates missing methods and classes inside tests on the fly by using Source Generators.
- DpdtInject - DI container based on C# Source Generators. Its goal is to remove everything possible from runtime and make resolving process as faster as we can. This is achieved by transferring huge piece of resolving logic to the compilation stage into the source generator.
- jakubsturc/talk-csharp-source-generators - contains 4 generators: AutoNotify, ConsoleWritelineHijack, HelloWorld and SettingsXml, plus nice presentation slides.
- Compile Time Method Execution Generator - proof of concept that allows executing a method during compilation, so that it can be really fast during runtime.
- Elskom/Sdk - Dumps git repository data to assembly level metadata attributes that can be checked at runtime for things like trapping if a user is using an possibly unstable build of the libraries built in the repository and so the user can see a message about it (and optionally opt into running the possibly unstable code).
- Heroicons.AspNetCore - Heroicons that are easy to use in ASP.NET Core MVC as TagHelpers.
- NetFabric.Hyperlinq - generates overloads for its extension methods.
- RestEase - uses Source Generator to generate interface implementations on compile time instead of in runtime via Reflection.Emit.
- WarHub/wham - generates code for immutable tree object graph based on red-green node approach used in Roslyn; generates custom XmlSerializer that supports C#9 records and ImmutableArray.