ClassFactory.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Logs;
  8. namespace cuidian.Common
  9. {
  10. public class ClassFactory
  11. {
  12. private static ClassFactory __singleton = new ClassFactory();
  13. private Dictionary<string, Assembly> __assemblyMaps = new Dictionary<string, Assembly>();
  14. private Dictionary<string, Type> __typeMaps = new Dictionary<string, Type>();
  15. private ClassFactory()
  16. { }
  17. public static ClassFactory Instance
  18. {
  19. get { return __singleton; }
  20. }
  21. public T CreateInstance<T>(string typeName, object[] args)
  22. {
  23. return __CreateInstance<T>(__GetType(typeName), args);
  24. }
  25. public T CreateInstance<T>(string typeName)
  26. {
  27. return __CreateInstance<T>(__GetType(typeName));
  28. }
  29. private T __CreateInstance<T>(Type type, object[] args)
  30. {
  31. object obj;
  32. try
  33. {
  34. obj = Activator.CreateInstance(type, args);//根据类型创建实例
  35. }
  36. catch (Exception ex)
  37. {
  38. LogHelper.Debug("创建类型:" + type.Name + "失败");
  39. throw ex;
  40. }
  41. return (T)obj;
  42. }
  43. private T __CreateInstance<T>(Type type)
  44. {
  45. object obj;
  46. try
  47. {
  48. obj = Activator.CreateInstance(type);//根据类型创建实例
  49. }
  50. catch (Exception ex)
  51. {
  52. LogHelper.Debug("创建类型:" + type.Name + "失败");
  53. throw ex;
  54. }
  55. return (T)obj;
  56. }
  57. private Type __GetType(string type)
  58. {
  59. if (!__typeMaps.ContainsKey(type))
  60. {
  61. __AddType(type);
  62. }
  63. return __typeMaps[type];
  64. }
  65. private void __AddType(string typeName)
  66. {
  67. string[] split = typeName.Split(new string[] { "," }, StringSplitOptions.None);
  68. Assembly asm = __GetAssembly(split[0]);
  69. Type type = asm.GetType(split[1]);
  70. if (type == null)
  71. {
  72. LogHelper.Debug("加载类型:" + split[1] + "失败");
  73. throw new Exception("加载类型:" + split[1] + "失败");
  74. }
  75. __typeMaps.Add(typeName, type);
  76. }
  77. private Assembly __GetAssembly(string assembly)
  78. {
  79. if (!__assemblyMaps.ContainsKey(assembly))
  80. {
  81. __AddAssembly(assembly);
  82. }
  83. return __assemblyMaps[assembly];
  84. }
  85. private void __AddAssembly(string assembly)
  86. {
  87. Assembly asm = Assembly.Load(assembly);
  88. __assemblyMaps.Add(assembly, asm);
  89. }
  90. }
  91. }