using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading; namespace Flyinsono.Client.Test { public interface IClientManager : IDisposable { } public class AppManager { private static bool _initialized; private static AppManager _instance; private readonly Dictionary _managers = new Dictionary(); /// /// The unique instance of app manager /// public static AppManager Instance => _instance ?? (_instance = new AppManager()); /// /// Register a manager with type and instance /// /// The manager instance public void RegisterManager(T instance) where T : IClientManager { var type = typeof(T); if (_managers.ContainsKey(type)) { throw new DuplicateNameException($"Type {type.Name} already exists."); } _managers[type] = instance; Logger.WriteLineInfo($"AppManager Manager {type.Name} registerd"); } /// /// Unregister a manager from app manager /// void UnRegisterManager() where T : IClientManager { var type = typeof(T); if (!_managers.ContainsKey(type)) { throw new DuplicateNameException($"Type {type} does not exists."); } _managers[type].Dispose(); _managers.Remove(type); } /// /// dispose all managers /// public void DisposeAllManagers() { foreach (var manager in _managers.Reverse()) { try { Logger.WriteLineInfo($"Disposing - {manager.Key?.Name}"); manager.Value.Dispose(); Logger.WriteLineInfo($"Disposed - {manager.Key?.Name}"); } catch (Exception e) { Logger.WriteLineError($"Dispose Manager {manager.Key} failed, ex: {e}"); } } } /// /// Get Manager by specified type /// /// /// public T GetManager() where T : IClientManager { var type = typeof(T); if (_managers.ContainsKey(type)) { return (T)_managers[type]; } throw new NullReferenceException($"Can not find instance for type{type}"); } /// /// Called at client start /// public void Initialize() { try { Logger.WriteLineInfo("AppManager Initialize begin"); RegisterCommonManagers(); } catch (Exception e) { Logger.WriteLineError($"Initialize Error:{e}"); } Logger.WriteLineInfo("AppManager Initialize end"); } private void RegisterCommonManagers() { if (_initialized) { Logger.WriteLineInfo("Has been Initialized"); return; } RegisterManager(new ClientTestManager()); Logger.WriteLineInfo("AppManager RegisterPluginCreators Register end"); _initialized = true; } } }