What is the difference between constructor injection and using IServiceProvider directly to resolve dependencies imperatively (service location)?
Short answer
Constructor injection explicitly declares a class's dependencies in its constructor signature, making them visible and enforced at compile time -- the preferred approach since it makes dependencies discoverable and testable.
Advertisement
AModel answer
Constructor injection explicitly declares a class's dependencies in its constructor signature, making them visible and enforced at compile time -- the preferred approach since it makes dependencies discoverable and testable. Service location instead has code call IServiceProvider.GetService<T>() imperatively wherever a dependency is needed, hiding the actual dependencies inside method bodies, an anti-pattern generally discouraged since it obscures a class's true requirements and complicates unit testing.
// Preferred: constructor injection, dependencies explicit
public class OrderService(IEmailSender emailSender) { ... }
// Anti-pattern: service location, hidden dependency
public class OrderService {
public void Process(IServiceProvider provider) {
var emailSender = provider.GetService<IEmailSender>(); // hidden, hard to test
}
}Real-world example
A code review rejects a pull request that resolves services via IServiceProvider.GetService<T>() inside a method body, requesting the dependency be moved to the constructor instead so it's visible in the class's public API and easily mockable in tests.
Likely follow-ups
- When is service location actually the pragmatic right choice (like plugin systems)?
- How does this relate to the broader Service Locator anti-pattern debate?
Related topics