using System; using System.Collections.Generic; using System.Linq; using AutoSaverPlugin.Contracts; using AutoSaverPlugin.Services; namespace AutoSaverPlugin.Shared; public static class ServiceProvider { private static readonly Dictionary> _services = new(); private static readonly Dictionary _singletonInstances = new(); public static void RegisterServiceAsTransient() where TImplementation : class, TInterface { _services[typeof(TInterface)] = () => CreateInstance(); } public static void RegisterServiceAsSingleton() where TImplementation : class, TInterface, new() { _services[typeof(TInterface)] = () => GetOrCreateSingletonInstance(typeof(TInterface), () => new TImplementation()); } public static void RegisterServiceAsSingleton(Func factory) { _services[typeof(TInterface)] = () => GetOrCreateSingletonInstance(typeof(TInterface), () => factory()); } public static T GetService() where T : class { return (T)GetService(typeof(T)); } private static object GetService(Type type) { if (_services.TryGetValue(type, out var serviceFactory)) { return serviceFactory(); } throw new InvalidOperationException($"Service of type {type} is not registered."); } private static T CreateInstance() where T : class { var type = typeof(T); var constructor = type.GetConstructors()[0]; var parameters = constructor.GetParameters(); var parameterInstances = parameters.Select(p => GetService(p.ParameterType)).ToArray(); return (T)constructor.Invoke(parameterInstances); } private static object GetOrCreateSingletonInstance(Type type, Func factory) { if (!_singletonInstances.TryGetValue(type, out var instance)) { instance = factory(); _singletonInstances[type] = instance; } return instance; } public static void Initialize() { RegisterServiceAsSingleton(); RegisterServiceAsSingleton(() => new ConfigurationManager(GetService())); RegisterServiceAsSingleton(() => new SceneTabStatusReporter(GetService())); RegisterServiceAsSingleton(() => new GDScriptStatusReporter(GetService())); RegisterServiceAsTransient(); RegisterServiceAsSingleton(() => new AutoSaveManager( GetService(), GetService(), GetService(), GetService(), GetService(), GetService() )); } }