AppEventSubscriber.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. var db = _serviceScope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
  27. await db.CopyNew().Insertable((SysLogEx)context.Source.Payload).ExecuteCommandAsync();
  28. }
  29. /// <summary>
  30. /// 发送异常邮件
  31. /// </summary>
  32. /// <param name="context"></param>
  33. /// <returns></returns>
  34. [EventSubscribe(CommonConst.SendErrorMail)]
  35. public async Task SendOrderErrorMail(EventHandlerExecutingContext context)
  36. {
  37. long.TryParse(App.HttpContext?.User.FindFirst(ClaimConst.TenantId)?.Value, out var tenantId);
  38. var tenant = await SysTenantQueryable.FirstAsync(t => t.Id == tenantId);
  39. var title = $"{tenant?.Title} 系统异常";
  40. await _serviceScope.ServiceProvider.GetRequiredService<SysEmailService>().SendEmail(JSON.Serialize(context.Source.Payload), title);
  41. }
  42. /// <summary>
  43. /// 释放服务作用域
  44. /// </summary>
  45. public void Dispose()
  46. {
  47. _serviceScope.Dispose();
  48. }
  49. }