ConfigManager.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. this.allConfig = 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. allConfig[iInit.ConfigName] = obj;
  57. }
  58. }
  59. public void Reload()
  60. {
  61. this.Load();
  62. }
  63. public T Get<T>(int type) where T : IType
  64. {
  65. var configManager = (ConfigCategory<T>)allConfig[typeof (T).Name];
  66. return configManager[type];
  67. }
  68. public Dictionary<int, T> GetAll<T>() where T : IType
  69. {
  70. var configManager = (ConfigCategory<T>)allConfig[typeof (T).Name];
  71. return configManager.GetAll();
  72. }
  73. public ConfigCategory<T> GetConfigManager<T>() where T : IType
  74. {
  75. return (ConfigCategory<T>)allConfig[typeof(T).Name];
  76. }
  77. }
  78. }