Constructor Injection
noun
say it: “kun-STRUK-ter in-JEK-shun” /kənˈstrʌktər ɪnˈdʒɛkʃən/
A class taking the objects it needs as constructor parameters instead of creating them itself.
What is Constructor Injection?
Constructor Injection — A class lists the objects it needs as constructor parameters and keeps them, instead of creating them with new. Whoever creates the class decides which ones to pass: the real email sender in the app, a fake one in a test.
class OrderService
{
private readonly IEmailSender email;
public OrderService(IEmailSender email) => this.email = email;
public void Place(Order order) => email.Send(order.CustomerEmail, "Thanks!");
}
In a sentence
- “With constructor injection, OrderService gets its email sender from whoever creates it.”
Level: Journeyman · More OOP terms at this level
Updated