forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBlogTranAOP.cs
More file actions
91 lines (77 loc) · 2.53 KB
/
BlogTranAOP.cs
File metadata and controls
91 lines (77 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using Blog.Core.Common;
using Blog.Core.IRepository.UnitOfWork;
using Castle.DynamicProxy;
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Blog.Core.AOP
{
/// <summary>
/// 事务拦截器BlogTranAOP 继承IInterceptor接口
/// </summary>
public class BlogTranAOP : IInterceptor
{
private readonly IUnitOfWork _unitOfWork;
public BlogTranAOP(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// 实例化IInterceptor唯一方法
/// </summary>
/// <param name="invocation">包含被拦截方法的信息</param>
public void Intercept(IInvocation invocation)
{
var method = invocation.MethodInvocationTarget ?? invocation.Method;
//对当前方法的特性验证
//如果需要验证
if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(UseTranAttribute)) is UseTranAttribute)
{
try
{
Console.WriteLine($"Begin Transaction");
_unitOfWork.BeginTran();
invocation.Proceed();
// 异步获取异常,先执行
if (IsAsyncMethod(invocation.Method))
{
var result = invocation.ReturnValue;
if (result is Task)
{
Task.WaitAll(result as Task);
}
}
_unitOfWork.CommitTran();
}
catch (Exception)
{
Console.WriteLine($"Rollback Transaction");
_unitOfWork.RollbackTran();
}
}
else
{
invocation.Proceed();//直接执行被拦截方法
}
}
private async Task SuccessAction(IInvocation invocation)
{
await Task.Run(() =>
{
//...
});
}
public static bool IsAsyncMethod(MethodInfo method)
{
return (
method.ReturnType == typeof(Task) ||
(method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
);
}
private async Task TestActionAsync(IInvocation invocation)
{
await Task.Run(null);
}
}
}