using System; using System.Linq; using System.Reflection; namespace ScreenConnect; public class Singleton where T : class { private static T instance; public static T Instance { get { if (instance == null) { lock (typeof(Singleton)) { if (instance == null) { instance = CreateInstance(); } } } return instance; } } private static T CreateInstance() { AssemblyName thisTypeAssemblyName = typeof(T).GetAssemblyX().GetName(); Exception lastException = null; foreach (Type type in (from singletonTypeAttribute in typeof(T).GetCustomAttributes() where singletonTypeAttribute.EnvironmentFlags == (EnvironmentInfo.Current & ((singletonTypeAttribute.EnvironmentFlagsMask == EnvironmentFlags.UnknownRuntime) ? singletonTypeAttribute.EnvironmentFlags : singletonTypeAttribute.EnvironmentFlagsMask)) select Extensions.TryGet(() => string.Format(singletonTypeAttribute.AssemblyName, thisTypeAssemblyName.Version, thisTypeAssemblyName.GetPublicKeyToken().ToHexString()).Pipe((string it) => new AssemblyName(it)).Pipe(Assembly.Load) .Pipe((Assembly it) => it.GetType(singletonTypeAttribute.TypeName).AssertNonNull()), out Type value2, out lastException, shouldTraceException: false).Pipe((bool _) => value2)).WhereNotNull().AppendIf(typeof(T), !typeof(T).IsAbstractX())) { if (Extensions.TryGet(() => (T)Activator.CreateInstance(type), out T value, out lastException)) { return value; } } throw new InvalidOperationException($"Cannot create singleton instance of {typeof(T)}", lastException); } }