|
Kanda Foundation 0.2.0
|
In Unity applications and games, dependencies often get tightly coupled with Singletons. This approach poses challenges to testability and modularity.
Singletons are a common pattern in Unity due to their simplicity and ease of use. However, they have several drawbacks:
To address these issues, the Kanda SDK provides a Service Locator framework, which allows for flexible and decoupled service registration and access throughout the application.
The AppServiceLocator maintains a static list of services that span the entire lifetime of the application unless explicitly cleared. It provides methods for both synchronous and asynchronous service retrieval, addressing common execution order issues.
Always register an interface for a service rather than a concrete class to enhance testability.
Get<T>()Assumes the service is already registered and throws an exception if not found. Suitable for services registered early in the application lifecycle.
GetAsync<T>()Waits for the service to become available, useful for handling execution order issues with MonoBehaviour scripts.
The ServiceContainer class is used under the hood in AppServiceLocator and can be utilized to create custom scoped service containers. This is useful for creating services scoped to a specific scene or other context-specific scenarios. It has the same API as AppServiceLocator but can be instantiated and managed separately.