TransactionInterceptor.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Threading.Tasks;
  3. using Castle.DynamicProxy;
  4. using FreeSql;
  5. using Admin.Core.Common;
  6. using Admin.Core.Extensions;
  7. using Admin.Core.Model.Output;
  8. namespace Admin.Core.Aop
  9. {
  10. public class TransactionInterceptor : IInterceptor
  11. {
  12. private readonly IUnitOfWork _unitOfWork;
  13. public TransactionInterceptor(IUnitOfWork unitOfWork)
  14. {
  15. _unitOfWork = unitOfWork;
  16. }
  17. public async void Intercept(IInvocation invocation)
  18. {
  19. var method = invocation.MethodInvocationTarget ?? invocation.Method;
  20. if (method.HasAttribute<TransactionAttribute>())
  21. {
  22. try
  23. {
  24. _unitOfWork.Open();
  25. invocation.Proceed();
  26. if (method.IsAsync())
  27. {
  28. if (invocation.Method.ReturnType == typeof(Task))
  29. {
  30. await (Task)invocation.ReturnValue;
  31. }
  32. else
  33. {
  34. AopHelper.CallGenericMethod(
  35. invocation,
  36. res =>
  37. {
  38. if (res == null)
  39. {
  40. return;
  41. }
  42. var responseOutput = res as IResponseOutput;
  43. if (responseOutput != null && !responseOutput.Success)
  44. {
  45. _unitOfWork.Rollback();
  46. }
  47. },
  48. ex =>
  49. {
  50. _unitOfWork.Rollback();
  51. });
  52. }
  53. }
  54. else
  55. {
  56. if (invocation.Method.ReturnType != typeof(void))
  57. {
  58. var responseOutput = invocation.ReturnValue as Task<IResponseOutput>;
  59. if (responseOutput != null && !responseOutput.Result.Success)
  60. {
  61. _unitOfWork.Rollback();
  62. }
  63. }
  64. }
  65. _unitOfWork.Commit();
  66. }
  67. catch (Exception)
  68. {
  69. _unitOfWork.Rollback();
  70. throw;
  71. }
  72. finally
  73. {
  74. _unitOfWork.Close();
  75. }
  76. }
  77. else
  78. {
  79. invocation.Proceed();
  80. }
  81. }
  82. }
  83. }