SqlSugarCoreProvider.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace SqlSugar
  8. {
  9. /// <summary>
  10. /// Partial SqlSugarScope
  11. /// </summary>
  12. public partial class SqlSugarScope : ISqlSugarClient, ITenant
  13. {
  14. private List<ConnectionConfig> _configs;
  15. private Action<SqlSugarClient> _configAction;
  16. protected virtual SqlSugarClient GetContext()
  17. {
  18. SqlSugarClient result = null;
  19. var key = _configs.GetHashCode().ToString();
  20. StackTrace st = new StackTrace(true);
  21. var methods = st.GetFrames();
  22. var isAsync = UtilMethods.IsAnyAsyncMethod(methods);
  23. if (methods.Length>=0)
  24. {
  25. foreach (var method in methods.Take(35))
  26. {
  27. var refType = method.GetMethod()?.ReflectedType;
  28. if (refType != null)
  29. {
  30. var getInterfaces = refType.Name.StartsWith("<") ? refType?.ReflectedType?.GetInterfaces() : refType?.GetInterfaces();
  31. if (getInterfaces != null && getInterfaces.Any(it => it.Name.IsIn("IJob")))
  32. {
  33. key = $"{key}IJob";
  34. break;
  35. }
  36. }
  37. }
  38. }
  39. if (isAsync)
  40. {
  41. result = GetAsyncContext(key);
  42. }
  43. else
  44. {
  45. result = GetThreadContext(key);
  46. }
  47. return result;
  48. }
  49. private SqlSugarClient GetAsyncContext(string key)
  50. {
  51. SqlSugarClient result = CallContextAsync<SqlSugarClient>.GetData(key);
  52. if (result == null)
  53. {
  54. List<ConnectionConfig> configList = GetCopyConfigs();
  55. CallContextAsync<SqlSugarClient>.SetData(key, new SqlSugarClient(configList));
  56. result = CallContextAsync<SqlSugarClient>.GetData(key);
  57. if (this._configAction != null)
  58. {
  59. this._configAction(result);
  60. }
  61. }
  62. return result;
  63. }
  64. private SqlSugarClient GetThreadContext(string key)
  65. {
  66. SqlSugarClient result = CallContextThread<SqlSugarClient>.GetData(key);
  67. if (result == null)
  68. {
  69. List<ConnectionConfig> configList = GetCopyConfigs();
  70. CallContextThread<SqlSugarClient>.SetData(key, new SqlSugarClient(configList));
  71. result = CallContextThread<SqlSugarClient>.GetData(key);
  72. if (this._configAction != null)
  73. {
  74. this._configAction(result);
  75. }
  76. }
  77. return result;
  78. }
  79. private List<ConnectionConfig> GetCopyConfigs()
  80. {
  81. return _configs.Select(it =>UtilMethods.CopyConfig(it)).ToList();
  82. }
  83. }
  84. }