Cratis C# engineering conventions
These are the house conventions Cratis maintainers apply across every
repository. They are conventions, not framework contracts: nothing here is
enforced by an analyzer unless this skill says so. Follow them for consistency;
do not claim the framework requires them.
Verified product sources
| Package |
Purpose |
Cratis.Fundamentals |
DI lifetime attributes and IInstancesOf<T> instance resolution |
Route near misses
- The question is what a Cratis product API does: resolve it against the
owning product repository, not against this style guide.
- The subject is a specification file: the specification conventions own the
Establish/Because/should_ pattern and the for_/when_ hierarchy.
- The subject is TypeScript or React: this skill covers C# only.
- The subject is repository structure or documentation: those are separate
workflows.
Quick reference
- Use current C# language features — records, primary constructors, pattern
matching, collection expressions.
var over an explicit type; the right-hand side already names the type.
- File-scoped namespace declarations.
using directives alphabetically sorted, single-line, unused ones removed.
- No regions. A file that needs them needs refactoring instead.
- No technical postfixes on type names: no
Impl, Service, Manager,
Handler, Base, Async.
- No
Exception suffix on exception types — AuthorNotFound, not
AuthorNotFoundException.
- Never throw a built-in exception type. Always define a domain exception.
record for events, commands, read models, concepts, and DTOs.
is null and is not null — never == null or != null.
- Blank line before the opening
{ of every block.
- A final
return sits on its own line.
- Private fields are
_camelCase; interfaces take the I prefix.
- American English everywhere — initialize, behavior, color, serialize.
- Every file starts with the repository license header.
Formatting
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace <RootNamespace>.<Feature>;
using <Namespace>.<First>;
using <Namespace>.<Second>;
// Blank line before the opening brace of every block
if (<condition>)
{
<statement>;
}
// Expression-bodied form for simple members
public string <PropertyName> => $"{<First>} {<Second>}";
// The final return stands alone
public <ReturnType> <MethodName>()
{
var result = <expression>;
return result;
}
Naming
| Artifact |
Convention |
Example |
| Type, method, public member |
PascalCase |
RegisterAuthor, AuthorId |
| Private field |
_camelCase |
_eventLog |
| Local variable |
camelCase |
authorId |
| Interface |
I prefix |
IEventLog |
| Exception type |
No Exception suffix |
AuthorNotFound |
| Feature folder |
Pluralized domain noun |
Authors/ |
| Concept file |
The concept name |
AuthorId.cs |
Avoid abbreviations unless they are universally known (Id, Xml, Json,
Url). Never add a prefix or postfix that names a technical role —
Controller, ViewModel, Handler, Manager, Factory, Base. Name after
the domain, not the pattern.
Where the detail lives
| Topic |
Reference |
Records, primary constructors, var, collections, nullable, async, pattern matching, XML documentation |
code-style.md |
| Custom exceptions, structured logging, dependency injection, service lifetimes, implementation discovery |
exceptions-logging-and-di.md |
| CUPID, cohesion over layers, ubiquitous language, immutability |
domain-philosophy.md |
Read the reference that covers the decision at hand rather than all three.
The two rules most often got wrong
Anything taking a scoped dependency is scoped or transient, never a
singleton. A singleton may not depend on anything that belongs to a tenant, a
user, or a request. Capturing a scoped collaborator does not throw — it silently
binds to the root scope's default namespace forever and returns empty results.
The fix is almost always to drop [Singleton], not to reach for
IServiceScopeFactory. See
exceptions-logging-and-di.md.
Enable it on an existing codebase in this order, or it will simply refuse to
start: turn it on locally first, fix everything it names, and only then let it
reach the deployed environments. Turning it on before the sweep converts a
silent multi-tenant bug into a production outage.
Use IInstancesOf<T>, never IEnumerable<T>, to enumerate implementations of
an abstraction. IEnumerable<T> only works when every implementation is
hand-registered, which defeats convention-based discovery.
Verify
- Every file carries the repository license header and a file-scoped namespace.
using directives are sorted, single-line, and free of unused entries.
- No regions, no technical postfixes, no
Exception suffix.
- Every thrown exception is a domain type deriving from
Exception with a
meaningful message and an XML <exception> or <summary> doc starting with
"The exception that is thrown when".
- No
catch block is empty or silently swallowing.
- Null checks use
is null / is not null, and no defensive check contradicts a
non-nullable annotation.
- Every public type, method, property, and operator carries multiline XML
documentation with
<param> and <returns> where applicable.
- No
[Singleton] takes a scoped dependency or holds tenant-, user-, or
request-bound state, and the host sets ValidateScopes and ValidateOnBuild
in every environment.
- No
services.Add*<TInterface, TImplementation>() registers a type that exists
to be discovered by convention.
- Text is American English.
- The solution builds with zero warnings and zero errors, and the affected
specifications pass.
1---2name: cratis-engineering-csharp-conventions-23description: Use when writing or reviewing C# house style in a Cratis repository, including naming, formatting and service lifetimes. Not for product API behavior or specification authoring.4license: LICENSE5metadata:6 source: https://skillmd.com/skills/cratis/cratis-engineering-csharp-conventions-27---89# Cratis C# engineering conventions1011These are the house conventions Cratis maintainers apply across every12repository. They are **conventions**, not framework contracts: nothing here is13enforced by an analyzer unless this skill says so. Follow them for consistency;14do not claim the framework requires them.1516## Verified product sources1718| Package | Purpose |19| --- | --- |20| `Cratis.Fundamentals` | DI lifetime attributes and `IInstancesOf<T>` instance resolution |2122## Route near misses2324- The question is what a Cratis product API *does*: resolve it against the25 owning product repository, not against this style guide.26- The subject is a specification file: the specification conventions own the27 `Establish`/`Because`/`should_` pattern and the `for_`/`when_` hierarchy.28- The subject is TypeScript or React: this skill covers C# only.29- The subject is repository structure or documentation: those are separate30 workflows.3132## Quick reference3334- Use current C# language features — records, primary constructors, pattern35 matching, collection expressions.36- `var` over an explicit type; the right-hand side already names the type.37- File-scoped namespace declarations.38- `using` directives alphabetically sorted, single-line, unused ones removed.39- No regions. A file that needs them needs refactoring instead.40- No technical postfixes on type names: no `Impl`, `Service`, `Manager`,41 `Handler`, `Base`, `Async`.42- No `Exception` suffix on exception types — `AuthorNotFound`, not43 `AuthorNotFoundException`.44- Never throw a built-in exception type. Always define a domain exception.45- `record` for events, commands, read models, concepts, and DTOs.46- `is null` and `is not null` — never `== null` or `!= null`.47- Blank line before the opening `{` of every block.48- A final `return` sits on its own line.49- Private fields are `_camelCase`; interfaces take the `I` prefix.50- American English everywhere — initialize, behavior, color, serialize.51- Every file starts with the repository license header.5253## Formatting5455```csharp56// Copyright (c) Cratis. All rights reserved.57// Licensed under the MIT license. See LICENSE file in the project root for full license information.5859namespace <RootNamespace>.<Feature>;6061using <Namespace>.<First>;62using <Namespace>.<Second>;6364// Blank line before the opening brace of every block65if (<condition>)66{67 <statement>;68}6970// Expression-bodied form for simple members71public string <PropertyName> => $"{<First>} {<Second>}";7273// The final return stands alone74public <ReturnType> <MethodName>()75{76 var result = <expression>;7778 return result;79}80```8182## Naming8384| Artifact | Convention | Example |85| --- | --- | --- |86| Type, method, public member | PascalCase | `RegisterAuthor`, `AuthorId` |87| Private field | `_camelCase` | `_eventLog` |88| Local variable | camelCase | `authorId` |89| Interface | `I` prefix | `IEventLog` |90| Exception type | No `Exception` suffix | `AuthorNotFound` |91| Feature folder | Pluralized domain noun | `Authors/` |92| Concept file | The concept name | `AuthorId.cs` |9394Avoid abbreviations unless they are universally known (`Id`, `Xml`, `Json`,95`Url`). Never add a prefix or postfix that names a technical role —96`Controller`, `ViewModel`, `Handler`, `Manager`, `Factory`, `Base`. Name after97the domain, not the pattern.9899## Where the detail lives100101| Topic | Reference |102| --- | --- |103| Records, primary constructors, `var`, collections, nullable, async, pattern matching, XML documentation | [code-style.md](references/code-style.md) |104| Custom exceptions, structured logging, dependency injection, service lifetimes, implementation discovery | [exceptions-logging-and-di.md](references/exceptions-logging-and-di.md) |105| CUPID, cohesion over layers, ubiquitous language, immutability | [domain-philosophy.md](references/domain-philosophy.md) |106107Read the reference that covers the decision at hand rather than all three.108109## The two rules most often got wrong110111**Anything taking a scoped dependency is scoped or transient, never a112singleton.** A singleton may not depend on anything that belongs to a tenant, a113user, or a request. Capturing a scoped collaborator does not throw — it silently114binds to the root scope's default namespace forever and returns empty results.115The fix is almost always to drop `[Singleton]`, not to reach for116`IServiceScopeFactory`. See117[exceptions-logging-and-di.md](references/exceptions-logging-and-di.md).118119Enable it on an existing codebase in this order, or it will simply refuse to120start: turn it on locally first, fix everything it names, and only then let it121reach the deployed environments. Turning it on before the sweep converts a122silent multi-tenant bug into a production outage.123124**Use `IInstancesOf<T>`, never `IEnumerable<T>`, to enumerate implementations of125an abstraction.** `IEnumerable<T>` only works when every implementation is126hand-registered, which defeats convention-based discovery.127128## Verify129130- Every file carries the repository license header and a file-scoped namespace.131- `using` directives are sorted, single-line, and free of unused entries.132- No regions, no technical postfixes, no `Exception` suffix.133- Every thrown exception is a domain type deriving from `Exception` with a134 meaningful message and an XML `<exception>` or `<summary>` doc starting with135 "The exception that is thrown when".136- No `catch` block is empty or silently swallowing.137- Null checks use `is null` / `is not null`, and no defensive check contradicts a138 non-nullable annotation.139- Every public type, method, property, and operator carries multiline XML140 documentation with `<param>` and `<returns>` where applicable.141- No `[Singleton]` takes a scoped dependency or holds tenant-, user-, or142 request-bound state, and the host sets `ValidateScopes` and `ValidateOnBuild`143 in every environment.144- No `services.Add*<TInterface, TImplementation>()` registers a type that exists145 to be discovered by convention.146- Text is American English.147- The solution builds with zero warnings and zero errors, and the affected148 specifications pass.