S8SqlSugarScopeFactory.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using SqlSugar;
  2. namespace Admin.NET.Plugin.AiDOP.Service.S8.Rules;
  3. /// <summary>
  4. /// S8-DYNAMIC-SQLSUGAR-SCOPE-FACTORY-1:S8 SQL evaluator 独立 SqlSugarScope 构造工厂。
  5. /// 职责:
  6. /// 1) 调用 S8DataSourceEndpointNormalizer 规范化 raw endpoint 并派生 EndpointHash;
  7. /// 2) 以 ConfigId="s8-eval-{endpointHash 前 16 位}" 构造 ConnectionConfig:
  8. /// 同 endpoint → 同 ConfigId,让 SqlSugar 内部按 ConfigId dedupe,
  9. /// 并让底层 ADO.NET 连接池按 normalized connection string 与主库共享;
  10. /// 3) 注入 S8EvaluatorGuard.ApplyCommandTimeout 显式 CommandTimeout:
  11. /// 独立 scope 不继承 SqlSugarSetup.SetDbAop 的全局 30s;
  12. /// 4) 返回 SqlSugarScope;不缓存、不持有长生命周期连接、不实现 IDisposable,
  13. /// 调用方负责 using var scope 自动 Dispose。
  14. /// 不读 endpoint 原文输出日志、不在异常 message 中携带 connection string 或密码。
  15. /// </summary>
  16. public sealed class S8SqlSugarScopeFactory : ITransient
  17. {
  18. private const int ConfigIdHashLength = 16;
  19. private const string ConfigIdPrefix = "s8-eval-";
  20. public SqlSugarScope CreateScope(string rawEndpoint, DbType dbType, int commandTimeoutSeconds)
  21. {
  22. var normalize = S8DataSourceEndpointNormalizer.Normalize(rawEndpoint);
  23. var configId = ConfigIdPrefix + normalize.EndpointHash.Substring(0, ConfigIdHashLength);
  24. var scope = new SqlSugarScope(new ConnectionConfig
  25. {
  26. ConfigId = configId,
  27. DbType = dbType,
  28. ConnectionString = normalize.NormalizedConnectionString,
  29. InitKeyType = InitKeyType.Attribute,
  30. IsAutoCloseConnection = true,
  31. });
  32. S8EvaluatorGuard.ApplyCommandTimeout(scope, commandTimeoutSeconds);
  33. return scope;
  34. }
  35. }