ConfigManager.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Common.Logger;
  5. namespace Common.Config
  6. {
  7. public class ConfigManager
  8. {
  9. private static ConfigManager instance = new ConfigManager();
  10. public static ConfigManager Instance
  11. {
  12. get
  13. {
  14. return instance;
  15. }
  16. }
  17. public Dictionary<Type, ICategory> allConfig;
  18. private ConfigManager()
  19. {
  20. }
  21. public void Load(Assembly assembly)
  22. {
  23. var localAllConfig = new Dictionary<Type, ICategory>();
  24. Type[] types = assembly.GetTypes();
  25. foreach (Type type in types)
  26. {
  27. object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
  28. Log.Debug(type.Name);
  29. if (attrs.Length == 0)
  30. {
  31. continue;
  32. }
  33. object obj = (Activator.CreateInstance(type));
  34. ICategory iCategory = obj as ICategory;
  35. if (iCategory == null)
  36. {
  37. throw new Exception(
  38. string.Format("class: {0} not inherit from ACategory", type.Name));
  39. }
  40. iCategory.BeginInit();
  41. iCategory.EndInit();
  42. localAllConfig[iCategory.ConfigType] = iCategory;
  43. }
  44. this.allConfig = localAllConfig;
  45. }
  46. public T Get<T>(int id) where T : AConfig
  47. {
  48. Type type = typeof (T);
  49. ICategory configCategory;
  50. if (!this.allConfig.TryGetValue(type, out configCategory))
  51. {
  52. throw new KeyNotFoundException(string.Format("ConfigManager not found key: {0}", type.FullName));
  53. }
  54. return ((ACategory<T>) configCategory)[id];
  55. }
  56. public T[] GetAll<T>() where T : AConfig
  57. {
  58. Type type = typeof(T);
  59. ICategory configCategory;
  60. if (!this.allConfig.TryGetValue(type, out configCategory))
  61. {
  62. throw new KeyNotFoundException(string.Format("ConfigManager not found key: {0}", type.FullName));
  63. }
  64. return ((ACategory<T>)configCategory).GetAll();
  65. }
  66. public T GetCategory<T>() where T : class, ICategory, new()
  67. {
  68. T t = new T();
  69. Type type = t.ConfigType;
  70. ICategory category;
  71. bool ret = this.allConfig.TryGetValue(type, out category);
  72. return ret? (T) category : null;
  73. }
  74. }
  75. }