DatabaseModule.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. using XGame.Framework.Asyncs;
  4. namespace XGame.Framework.Database
  5. {
  6. public partial class DatabaseModule : IDatabaseModule, IDisposable
  7. {
  8. private readonly Dictionary<string, IAsync> _loadingAsyncMap = new();
  9. private readonly Dictionary<string, object> _talbeRepoMap = new();
  10. TTable IDatabaseModule.GetByKey<TTable, TRepository>(long key)
  11. {
  12. var tableName = typeof(TTable).Name;
  13. if (_talbeRepoMap.TryGetValue(tableName, out var tableRepo))
  14. {
  15. return (tableRepo as TRepository).GetByKey(key);
  16. }
  17. return default;
  18. }
  19. TTable IDatabaseModule.GetByIndex<TTable, TRepository>(int index)
  20. {
  21. var tableName = typeof(TTable).Name;
  22. if (_talbeRepoMap.TryGetValue(tableName, out var tableRepo))
  23. {
  24. return (tableRepo as TRepository).GetByIndex(index);
  25. }
  26. return default;
  27. }
  28. TTable[] IDatabaseModule.GetAll<TTable, TRepository>()
  29. {
  30. var tableName = typeof(TTable).Name;
  31. if (_talbeRepoMap.TryGetValue(tableName, out var tableRepo))
  32. {
  33. return (tableRepo as TRepository).GetAllTables();
  34. }
  35. return null;
  36. }
  37. IDatabaseAsync<TTable> IDatabaseModule.LoadAsync<TTable, TRepository>(string tableName)
  38. {
  39. if (_talbeRepoMap.ContainsKey(tableName))
  40. {
  41. Log.Debug($"配置表重复加载. Name:{tableName}");
  42. return null;
  43. }
  44. if (_loadingAsyncMap.TryGetValue(tableName, out var loadingAsync))
  45. {
  46. return loadingAsync as IDatabaseAsync<TTable>;
  47. }
  48. var dbAsync = new DatabaseAsync<TTable>(tableName);
  49. _loadingAsyncMap.Add(tableName, dbAsync);
  50. dbAsync.On((_) =>
  51. {
  52. _loadingAsyncMap.Remove(tableName);
  53. var tableRepo = dbAsync.GetResult<TRepository>();
  54. if (tableRepo != null)
  55. {
  56. _talbeRepoMap[tableName] = tableRepo;
  57. }
  58. });
  59. dbAsync.Start();
  60. return dbAsync;
  61. }
  62. void IDatabaseModule.Unload(string tableName)
  63. {
  64. if (_talbeRepoMap.ContainsKey(tableName))
  65. {
  66. _talbeRepoMap.Remove(tableName);
  67. return;
  68. }
  69. if (_loadingAsyncMap.TryGetValue(tableName, out var loadAsync))
  70. {
  71. loadAsync.RemoveAll();
  72. _loadingAsyncMap.Remove(tableName);
  73. }
  74. }
  75. void IDisposable.Dispose()
  76. {
  77. foreach(var item in _loadingAsyncMap)
  78. {
  79. item.Value.RemoveAll();
  80. }
  81. _loadingAsyncMap.Clear();
  82. foreach(var item in _talbeRepoMap)
  83. {
  84. (item.Value as IDisposable)?.Dispose();
  85. }
  86. _talbeRepoMap.Clear();
  87. }
  88. }
  89. }