DatabaseModule.cs 2.9 KB

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