Sobes.tech
Junior — Middle

Have you used the Service Locator pattern in your projects for managed access to services?

sobes.tech AI

Answer from AI

Yes, I have used the Service Locator pattern in projects for centralized access to services and application components.

The Service Locator is an object that knows how to obtain the required service (for example, through a DI container or factory) and provides it to clients upon request. This simplifies dependency management, especially in large applications.

Example in C#:

public interface IService {}
public class MyService : 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 MyService());
var service = ServiceLocator.Get<IService>();

However, it is important to remember that the Service Locator can hide dependencies and complicate testing, so modern projects often prefer explicit dependency injection.