Kanda Foundation 0.2.0
Loading...
Searching...
No Matches
Dependency Inversion with Services

In Unity applications and games, dependencies often get tightly coupled with Singletons. This approach poses challenges to testability and modularity.

The Problem with Singletons

Singletons are a common pattern in Unity due to their simplicity and ease of use. However, they have several drawbacks:

  1. Tight Coupling: Singletons often lead to tight coupling between components, making it difficult to change or replace parts of the system.
  2. Testing Challenges: Singletons are difficult to mock or replace in unit tests, making automated testing challenging.
  3. Hidden Dependencies: Dependencies on singletons are often implicit, making the codebase harder to understand and maintain.

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.

AppServiceLocator

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.

Registering Services

Always register an interface for a service rather than a concrete class to enhance testability.

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
private static void RegisterMyService()
{
IMyService myService = new MyService();
AppServiceLocator.Register(myService);
}

Getting Services

Synchronous with Get<T>()

Assumes the service is already registered and throws an exception if not found. Suitable for services registered early in the application lifecycle.

IMyService myService = AppServiceLocator.Get<IMyService>();
Asynchronous with GetAsync<T>()

Waits for the service to become available, useful for handling execution order issues with MonoBehaviour scripts.

private async void Awake()
{
var myService = await AppServiceLocator.GetAsync<IMyService>();
IMyOtherService otherService = new MyOtherService(myService);
AppServiceLocator.Register(otherService);
}

ServiceContainer

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.