Class ServiceLocator
- Namespace
- WitShells.DesignPatterns.Core
A global, type-keyed Service Locator that acts as a lightweight alternative to dependency injection. Systems register their implementations once and any other system can retrieve them by interface/type without knowing the concrete class.
public static class ServiceLocator
- Inheritance
-
ServiceLocator
- Inherited Members
Examples
// Registration (e.g. in a bootstrap scene)
ServiceLocator.Register<IAudioService>(new AudioService());
// Retrieval (anywhere in the project)
var audio = ServiceLocator.Get<IAudioService>();
audio.PlaySound("explosion");
Remarks
When to use: Small-to-medium projects where full DI container setup is overkill. Caution: Overuse hides dependencies and makes unit testing harder. Prefer constructor injection or MonoSingleton<T> for single-instance MonoBehaviours.
Methods
Clear()
Removes all registered services from the locator.
public static void Clear()
Get<TService>()
Retrieves the registered service of type TService.
public static TService Get<TService>()
Returns
- TService
The registered service instance.
Type Parameters
TServiceThe type to look up.
Exceptions
- InvalidOperationException
Thrown when no service of this type has been registered.
Register<TService>(TService)
Registers a service instance under its type key TService.
If a service of the same type is already registered it is replaced.
public static void Register<TService>(TService service)
Parameters
serviceTServiceThe service instance to register.
Type Parameters
TServiceThe interface or concrete type used as the lookup key.
Unregister<TService>()
Removes the registered service for type TService.
public static void Unregister<TService>()
Type Parameters
TServiceThe type whose registration should be removed.