ConfigManager.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. namespace Component
  6. {
  7. public class ConfigManager
  8. {
  9. private static readonly ConfigManager instance = new ConfigManager();
  10. public static ConfigManager Instance
  11. {
  12. get
  13. {
  14. return instance;
  15. }
  16. }
  17. public Dictionary<string, object> allConfig;
  18. private ConfigManager()
  19. {
  20. this.Load();
  21. }
  22. private void Load()
  23. {
  24. var localAllConfig = new Dictionary<string, object>();
  25. string currentDir = AppDomain.CurrentDomain.BaseDirectory;
  26. Type[] types = typeof (ConfigManager).Assembly.GetTypes();
  27. foreach (var type in types)
  28. {
  29. object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
  30. if (attrs.Length == 0)
  31. {
  32. continue;
  33. }
  34. object obj = (Activator.CreateInstance(type));
  35. var iInit = obj as IConfigInitialize;
  36. if (iInit == null)
  37. {
  38. throw new Exception(string.Format("class {0} is not IConfigInitialize",
  39. type.Name));
  40. }
  41. var iSupportInitialize = obj as ISupportInitialize;
  42. if (iSupportInitialize != null)
  43. {
  44. iSupportInitialize.BeginInit();
  45. }
  46. string configDir = Path.Combine(currentDir,
  47. ((ConfigAttribute) attrs[0]).RelativeDirectory);
  48. if (!Directory.Exists(configDir))
  49. {
  50. throw new Exception(string.Format("not found config dir: {0}", configDir));
  51. }
  52. iInit.Init(configDir);
  53. if (iSupportInitialize != null)
  54. {
  55. iSupportInitialize.EndInit();
  56. }
  57. localAllConfig[iInit.ConfigName] = obj;
  58. }
  59. this.allConfig = localAllConfig;
  60. }
  61. public void Reload()
  62. {
  63. this.Load();
  64. }
  65. public T Get<T>(int type) where T : IType
  66. {
  67. var configManager = (ConfigCategory<T>) this.allConfig[typeof (T).Name];
  68. return configManager[type];
  69. }
  70. public Dictionary<int, T> GetAll<T>() where T : IType
  71. {
  72. var configManager = (ConfigCategory<T>) this.allConfig[typeof (T).Name];
  73. return configManager.GetAll();
  74. }
  75. public ConfigCategory<T> GetConfigManager<T>() where T : IType
  76. {
  77. return (ConfigCategory<T>) this.allConfig[typeof (T).Name];
  78. }
  79. }
  80. }