Singleton.cs 944 B

1234567891011121314151617181920212223242526
  1. namespace Admin.NET.Core;
  2. /// <summary>
  3. /// 单例泛型类
  4. /// </summary>
  5. /// <typeparam name="T"></typeparam>
  6. public abstract class Singleton<T> where T : class
  7. {
  8. private static readonly Lazy<T> _instance
  9. = new Lazy<T>(() =>
  10. {
  11. var ctors = typeof(T).GetConstructors(
  12. BindingFlags.Instance
  13. | BindingFlags.NonPublic
  14. | BindingFlags.Public);
  15. if (ctors.Count() != 1)
  16. throw new InvalidOperationException($"Type {typeof(T)} must have exactly one constructor.");
  17. var ctor = ctors.SingleOrDefault(c => !c.GetParameters().Any() && c.IsPrivate);
  18. if (ctor == null)
  19. throw new InvalidOperationException(
  20. $"The constructor for {typeof(T)} must be private and take no parameters.");
  21. return (T)ctor.Invoke(null);
  22. });
  23. public static T Instance => _instance.Value;
  24. }