primary constructor
Constructor parameters written straight after a class name, as in class ProductService(IProductRepository repository), which stay in scope for the whole class body.
In more detail
Added for classes in C# 12, it removes the private readonly field and the assignment that constructor injection used to need. Records have had primary constructors from the start.
Related terms
- constructor — A special method that runs when an object is created and receives whatever the object needs in order to exist.
- dependency injection — Giving an object the collaborators it needs from outside, usually through its constructor, instead of letting it create or look them up itself.
- readonly — A modifier, in languages such as C# and TypeScript, that lets a field or property be assigned only when it is initialised, never afterwards.
- record — A C# type declared with the record keyword for data, for which the compiler generates a constructor, properties, value equality, a readable ToString and with-expression copying.
Taught in
- Classes, Interfaces, and Object-Oriented C# — Modern .NET Core, C# & Enterprise Microservices
- The Dependency Injection Container: Scopes and Lifetimes — Modern .NET Core, C# & Enterprise Microservices
- The Options Pattern: Strongly Typed Configuration — Modern .NET Core, C# & Enterprise Microservices
- Entity Framework Core: Code First and Migrations — Modern .NET Core, C# & Enterprise Microservices