Skip to content

Best Practices

Building a Roslyn toolkit is more than writing a generator. You're shipping a developer experience — attributes they see, diagnostics they trust, code fixes they click, and tests that prove it all works. These guides cover the patterns that make Roslyn projects maintainable at scale.

Guides

  • Project Organization

    Five-layer architecture — Attributes, Projection, Generators, Analyzers, Code Fixes — with clear dependency rules, file conventions, and single-package NuGet bundling.

  • End-to-End Walkthrough

    Trace a complete feature ([StrongId]) across all five layers with real production code from the Deepstaging source.

  • Projection Pattern

    AttributeQuery types, [PipelineModel] records, and query extensions — the single source of truth that both generators and analyzers consume.

  • Generators

    Thin generators, Writer extension methods, ForAttribute, Combine overloads, and OptionalEmit patterns.

  • Analyzers

    One-method analyzers for every symbol type, multi-diagnostic analyzers, assembly attribute analyzers, build property access, and tracked file detection.

  • Code Fixes

    Code fix base classes, pre-built actions, project-level fixes, and ManagedPropsFile for MSBuild property edits.

  • Testing

    RoslynTestBase, generator snapshot tests, analyzer diagnostic assertions, code fix verification, and Scriban template testing.

The Short Version

  1. Separate concerns — Attributes, Projection, Generators, Analyzers, and Code Fixes are distinct projects with enforced dependency rules.
  2. Projection is the source of truth — Both generators and analyzers consume the same queries and models. Never interpret attributes twice.
  3. Generators are thin — Pipeline wiring only. The Projection layer builds models, Writer extensions emit code.
  4. Analyzers are single-purpose — One class, one rule, one boolean. The base class handles everything else.
  5. Code fixes pair with analyzers — Same diagnostic ID, one-click resolution. Ship both together.
  6. [PipelineModel] for caching — Roslyn's incremental pipeline needs correct equality. The attribute generates it for you.
  7. Test everything — Generator snapshots, analyzer diagnostics, code fix output. RoslynTestBase makes it painless.

Reference Projects

Project What You'll Find
dotnet new roslynkit Scaffolded starter with all five layers, CI, docs, and packaging
Deepstaging source Production suite — 6 generators, 50+ analyzers, 20+ code fixes
eShop samples How end-users consume generated code in real applications