Back to results for “Dependency Injection”
C# › Dependency Injection & IoC Principles

How does constructor injection differ from property (setter) injection, and why is constructor injection generally preferred?

Intermediate

Answer

Constructor injection passes dependencies through the constructor, guaranteeing an object is NEVER in a partially-initialized state and making dependencies clearly visible in the class's public API; property injection sets dependencies via public properties AFTER construction, which can leave an object usable-but-broken if a required property is forgotten, and hides the true dependency requirements from the constructor signature.
// Constructor injection: dependency is guaranteed present and visible
public class OrderService {
  private readonly ILogger _logger;
  public OrderService(ILogger logger) { _logger = logger; } // impossible to construct without it
}

// Property injection: risky, can be forgotten
public class OrderServiceRisky {
  public ILogger? Logger { get; set; } // might be null if forgotten!
}
Real-world example Preferring constructor injection for REQUIRED dependencies, reserving property injection (if used at all) for genuinely OPTIONAL ones.

Common follow-ups: In what specific, narrower scenarios might property injection still be a reasonable choice?