Back to results for “Dependencies”
.NET › Dependency Injection

What is the difference between constructor injection and service location (using IServiceProvider directly to resolve dependencies)?

Intermediate

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 makes unit testing harder, though occasionally necessary for truly dynamic runtime resolution scenarios).
// Preferred: constructor injection, dependencies explicit
public class OrderService {
    public OrderService(IEmailSender emailSender) { ... }  // clear requirement
}

// 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.

Common 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?