C# 12 primary constructors can significantly reduce boilerplate in DI service classes by eliminating field declarations, constructor bodies, and assignments. The author shares their experience switching to primary constructors for ASP.NET Core services, explaining the key pitfall: parameters are captured as mutable variables, not readonly fields, meaning accidental reassignment compiles without warning. The recommended approach is to use primary constructors freely in DI service classes where accidental reassignment is unlikely, but fall back to traditional constructors for validation-heavy types, multiple constructor overloads, or classes with too many dependencies.
Table of contents
What Changed My MindWhere I Use Them Most: DI Service ClassesEntity Construction (With a Caveat)The Pitfall That Almost Stopped MeWhere I Still Use Traditional ConstructorsSummary4 Comments
Sort: