using System; using System.Collections.Generic; using UnityEngine; using Zeitsand.Service.Interfaces; namespace Zeitsand.Service.Core { // // Simple generic service locator with added lifetime managment // Ment for core services like Persistance or other no monobehavior services // Services need to implement the IService interface for initialization and shutdown (enforced) // Services should be registered with their interfaces, so they can be replaced with stubs for testing if needed // Parameters should be passed via constructor while instancing the class // public static class Services { private static readonly Dictionary ServiceMap = new(); private static readonly List ServiceOrder = new(); public static void Register(T service) { if (service is IService) { ServiceMap.Add(typeof(T), service); ServiceOrder.Add(service); Debug.Log("Service registered: " + typeof(T)); } else { Debug.LogError( $"Service {service.GetType()} is not an IService. " + "This is not allowed. Please implement the IService interface." ); } } // should be called from the bootstrap ( after registering all services public static void Initialize() { // initialize in order of registration foreach(IService service in ServiceOrder) service.Initialize(); } // should be called from bootstrap in onApplicationQuit public static void Shutdown() { // shutdown in reverse order of registration for (int i = ServiceOrder.Count - 1; i >= 0; i--) { if (ServiceOrder[i] is IService service) { service.Shutdown(); } } // Clear the service map and order list. ServiceMap.Clear(); ServiceOrder.Clear(); } public static T Get() => (T)ServiceMap[typeof(T)]; } }