Junior — Middle
Can you explain the main differences between Service Locator and Inversion of Control (IoC) approaches?
sobes.tech AI
Answer from AI
Service Locator and Inversion of Control (IoC) are dependency management patterns, but they differ in approach.
-
Service Locator is an object that provides dependencies on demand. Components themselves contact the service locator to obtain the required services.
Example:
var service = ServiceLocator.GetService<IMyService>(); service.DoWork(); -
Inversion of Control (IoC) is a principle where the creation and provision of dependencies are delegated to an external container or framework. Dependencies are injected into components via constructors, properties, or methods.
Example of constructor injection:
public class MyClass { private readonly IMyService _service; public MyClass(IMyService service) { _service = service; } public void DoWork() { _service.DoWork(); } }
Main differences:
- In Service Locator, the component requests dependencies itself, which can complicate testing and violates the principle of explicit dependencies.
- In IoC, dependencies are passed from outside, improving modularity and easing testing.
IoC is considered a more modern and preferred approach for dependency management.