Junior — Middle
Can you explain the principles of the Service Locator pattern and its purpose?
sobes.tech AI
Answer from AI
The Service Locator pattern is used for managing dependencies in an application. It provides a centralized object (locator) responsible for supplying the required services or components upon request.
Main principles:
- There is a global or local registry of services within the application.
- Clients request services from the locator without creating them directly.
- The locator encapsulates the logic for creating and configuring services.
Purpose:
- Simplify access to services.
- Centralize dependency configuration.
- Reduce coupling between components.
Example in C#:
public interface IService {}
public class ServiceA : IService {}
public class ServiceLocator
{
private static readonly Dictionary<Type, object> services = new Dictionary<Type, object>();
public static void Register<T>(T service) where T : class
{
services[typeof(T)] = service;
}
public static T Get<T>() where T : class
{
services.TryGetValue(typeof(T), out var service);
return service as T;
}
}
// Usage
ServiceLocator.Register<IService>(new ServiceA());
var service = ServiceLocator.Get<IService>();
However, the pattern is criticized for hidden dependencies and complicating testing, so it is often preferable to use Dependency Injection.