.NET › Dependency Injection
How does the DI container handle constructor injection when a class has multiple constructors?
IntermediateAnswer
The default ASP.NET Core DI container requires exactly one constructor be resolvable (all its parameter types must be registered services) -- if multiple constructors could theoretically be satisfied, or if the class has multiple public constructors at all in some scenarios, the container throws an exception rather than guessing which one to use, since implicit 'pick the best constructor' behavior (common in other DI frameworks) is intentionally not supported by the built-in container to avoid ambiguity.
public class OrderService {
// Having two constructors like this causes issues with the built-in container:
public OrderService(IEmailSender emailSender) { ... }
public OrderService(IEmailSender emailSender, ILogger<OrderService> logger) { ... }
// Built-in container: ambiguous, throws at resolution time
}
// Fix: use exactly one constructor, or use a third-party container supporting thisReal-world example A team migrating from a third-party DI container (which supported multiple constructor overloads with fallback resolution) to the built-in ASP.NET Core container hits runtime errors until they consolidate each service down to a single constructor.