ConfigManager.cs 2.0 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", type.Name));
  39. }
  40. var iSupportInitialize = obj as ISupportInitialize;
  41. if (iSupportInitialize != null)
  42. {
  43. iSupportInitialize.BeginInit();
  44. }
  45. string configDir = Path.Combine(
  46. currentDir, ((ConfigAttribute)attrs[0]).RelativeDirectory);
  47. if (!Directory.Exists(configDir))
  48. {
  49. throw new Exception(string.Format("not found config dir: {0}", configDir));
  50. }
  51. iInit.Init(configDir);
  52. if (iSupportInitialize != null)
  53. {
  54. iSupportInitialize.EndInit();
  55. }
  56. localAllConfig[iInit.ConfigName] = obj;
  57. }
  58. this.allConfig = localAllConfig;
  59. }
  60. public void Reload()
  61. {
  62. this.Load();
  63. }
  64. public T Get<T>(int type) where T : IType
  65. {
  66. var configManager = (ConfigCategory<T>)allConfig[typeof (T).Name];
  67. return configManager[type];
  68. }
  69. public Dictionary<int, T> GetAll<T>() where T : IType
  70. {
  71. var configManager = (ConfigCategory<T>)allConfig[typeof (T).Name];
  72. return configManager.GetAll();
  73. }
  74. public ConfigCategory<T> GetConfigManager<T>() where T : IType
  75. {
  76. return (ConfigCategory<T>)allConfig[typeof(T).Name];
  77. }
  78. }
  79. }