ObjectFactory.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. namespace SKMC.Api.Common
  4. {
  5. /// <summary>
  6. /// <p>接口工厂</p>
  7. /// <br>类似IOC容器, 可将接口与实例注册绑定, 在需要调用接口时获取实例</br>
  8. /// <br>Resolve获取单例, Create创建新实例</br>
  9. /// </summary>
  10. public class ObjectFactory
  11. {
  12. private static readonly ILogger log = LogFactory.Get();
  13. private static readonly Dictionary<Type, Dictionary<string, object>> container = new Dictionary<Type, Dictionary<string, object>>();
  14. /// <summary>
  15. /// 注册接口实例
  16. /// </summary>
  17. /// <typeparam name="T"></typeparam>
  18. /// <param name="obj"></param>
  19. /// <param name="name"></param>
  20. public static void Register<T>(object obj, string name = "default")
  21. {
  22. Type type = typeof(T);
  23. if (!container.ContainsKey(type))
  24. {
  25. container[type] = new Dictionary<string, object>();
  26. }
  27. //else
  28. //{
  29. // throw new SystemException($"Register Failed, Cannot Register SameType: {type.Name}");
  30. //}
  31. container[type][name] = obj;
  32. log.Debug($"Register {type.Name} success");
  33. }
  34. /// <summary>
  35. /// 反注册接口实例, 重复注册前需要反注册
  36. /// </summary>
  37. /// <typeparam name="T"></typeparam>
  38. public static void UnRegister<T>()
  39. {
  40. Type type = typeof(T);
  41. if (container.ContainsKey(type))
  42. {
  43. bool result = container.Remove(type);
  44. log.Debug($"UnRegister Type: {type.Name}: {result}");
  45. }
  46. }
  47. /// <summary>
  48. /// 解析接口实例(单例)
  49. /// </summary>
  50. /// <typeparam name="T"></typeparam>
  51. /// <param name="name"></param>
  52. /// <returns></returns>
  53. public static T Resolve<T>(string name = "default")
  54. {
  55. Type type = typeof(T);
  56. if (container.ContainsKey(type) && container[type].ContainsKey(name))
  57. {
  58. object obj = (T)container[type][name];
  59. //log.Debug($"Create {type.Name} success, obj: {obj.GetHashCode()}");
  60. return (T)obj;
  61. }
  62. throw new SystemException($"Resolve Faild, No object for [{type}] with name [{name}] found.");
  63. }
  64. /// <summary>
  65. /// 创建接口实例(多例)
  66. /// </summary>
  67. /// <typeparam name="T"></typeparam>
  68. /// <param name="name"></param>
  69. /// <returns></returns>
  70. public static T Create<T>(string name = "default")
  71. {
  72. Type type = typeof(T);
  73. if (container.ContainsKey(type) && container[type].ContainsKey(name))
  74. {
  75. object objectNow = container[type][name];
  76. object objectNew = Activator.CreateInstance(objectNow.GetType());
  77. //log.Debug($"Create {type.Name} success, obj: {objectNew.GetHashCode()}");
  78. return (T)objectNew;
  79. }
  80. throw new SystemException($"Create Faild, No object for [{type}] with name [{name}] found.");
  81. }
  82. }
  83. }