SingletonCreator.cs 630 B

12345678910111213141516171819
  1. using System;
  2. using System.Reflection;
  3. namespace IFramework.Singleton
  4. {
  5. static class SingletonCreator
  6. {
  7. public static T CreateSingleton<T>() where T : class, ISingleton
  8. {
  9. var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
  10. var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
  11. if (ctor == null) throw new Exception("Non-Public Constructor() not found! in " + typeof(T));
  12. var retInstance = ctor.Invoke(null) as T;
  13. retInstance.OnSingletonInit();
  14. return retInstance;
  15. }
  16. }
  17. }