AppEventSubscriber.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. namespace Admin.NET.Core;
  7. /// <summary>
  8. /// 事件订阅
  9. /// </summary>
  10. public class AppEventSubscriber : IEventSubscriber, ISingleton, IDisposable
  11. {
  12. private static readonly ISugarQueryable<SysTenant> SysTenantQueryable = App.GetService<ISqlSugarClient>().Queryable<SysTenant>();
  13. private readonly IServiceScope _serviceScope;
  14. public AppEventSubscriber(IServiceScopeFactory scopeFactory)
  15. {
  16. _serviceScope = scopeFactory.CreateScope();
  17. }
  18. /// <summary>
  19. /// 增加异常日志
  20. /// </summary>
  21. /// <param name="context"></param>
  22. /// <returns></returns>
  23. [EventSubscribe(CommonConst.AddExLog)]
  24. public async Task CreateExLog(EventHandlerExecutingContext context)
  25. {
  26. // 切换日志独立数据库
  27. var db = SqlSugarSetup.ITenant.IsAnyConnection(SqlSugarConst.LogConfigId)
  28. ? SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.LogConfigId)
  29. : SqlSugarSetup.ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  30. await db.CopyNew().Insertable((SysLogEx)context.Source.Payload).ExecuteCommandAsync();
  31. }
  32. /// <summary>
  33. /// 发送异常邮件
  34. /// </summary>
  35. /// <param name="context"></param>
  36. /// <returns></returns>
  37. [EventSubscribe(CommonConst.SendErrorMail)]
  38. public async Task SendOrderErrorMail(EventHandlerExecutingContext context)
  39. {
  40. long.TryParse(App.HttpContext?.User.FindFirst(ClaimConst.TenantId)?.Value, out var tenantId);
  41. var tenant = await SysTenantQueryable.FirstAsync(t => t.Id == tenantId);
  42. var title = $"{tenant?.Title} 系统异常";
  43. await _serviceScope.ServiceProvider.GetRequiredService<SysEmailService>().SendEmail(JSON.Serialize(context.Source.Payload), title);
  44. }
  45. /// <summary>
  46. /// 释放服务作用域
  47. /// </summary>
  48. public void Dispose()
  49. {
  50. _serviceScope.Dispose();
  51. }
  52. }