|
- using System;
- using System.Collections.Generic;
- using UnityEngine;
-
- namespace SUISS.Core
- {
- public class ServiceLocator
- {
- private static ServiceLocator Instance
- {
- get
- {
- if (ServiceLocator._instance == null)
- {
- ServiceLocator._instance = new ServiceLocator();
- }
- return ServiceLocator._instance;
- }
- }
-
- public static T Find<T>()
- {
- ServiceLocator instance = ServiceLocator.Instance;
- if (!instance._services.ContainsKey(typeof(T)))
- {
- UnityEngine.Debug.LogWarning("Could not find Service of type \"" + typeof(T).ToString() + "\", returning default.");
- return default(T);
- }
- object obj = instance._services[typeof(T)];
- if (ServiceLocator.CheckForHiddenNull(obj))
- {
- ServiceLocator.UnregisterServiceObject<T>();
- return default(T);
- }
- return (T)((object)obj);
- }
-
- public static void RegistorServiceObject<T>(T serviceObject)
- {
- ServiceLocator instance = ServiceLocator.Instance;
- if (serviceObject == null)
- {
- UnityEngine.Debug.LogError("Trying to bind null object to " + typeof(T).ToString() + "!");
- return;
- }
- if (instance._services.ContainsKey(typeof(T)))
- {
- object service = instance._services[typeof(T)];
- if (!ServiceLocator.CheckForHiddenNull(service))
- {
- UnityEngine.Debug.LogError("Interface " + typeof(T).ToString() + " already registored with service locator!");
- return;
- }
- UnityEngine.Debug.LogWarning(string.Format("Removing (hidden) 'null' UnityEngine.Object {0} from service registory", typeof(T).Name));
- ServiceLocator.UnregisterServiceObject<T>();
- }
- instance._services.Add(typeof(T), serviceObject);
- }
-
- public static void UnregisterServiceObject<T>()
- {
- ServiceLocator instance = ServiceLocator.Instance;
- if (!instance._services.ContainsKey(typeof(T)))
- {
- UnityEngine.Debug.LogWarning("Interface " + typeof(T).ToString() + " was not registered with service locator!");
- return;
- }
- instance._services.Remove(typeof(T));
- }
-
- public static bool WasRegistered<T>()
- {
- ServiceLocator instance = ServiceLocator.Instance;
- if (!instance._services.ContainsKey(typeof(T)))
- {
- return false;
- }
- object service = instance._services[typeof(T)];
- if (ServiceLocator.CheckForHiddenNull(service))
- {
- ServiceLocator.UnregisterServiceObject<T>();
- return false;
- }
- return true;
- }
-
- private static bool CheckForHiddenNull(object service)
- {
- return service == null || service.Equals(null);
- }
-
- private static ServiceLocator _instance;
-
- private Dictionary<Type, object> _services = new Dictionary<Type, object>();
- }
- }
|