-
Notifications
You must be signed in to change notification settings - Fork 446
/
Copy pathILEmitHttpApiActivator.cs
215 lines (180 loc) · 9.74 KB
/
ILEmitHttpApiActivator.cs
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using WebApiClientCore.Exceptions;
using WebApiClientCore.Internals;
namespace WebApiClientCore.Implementations
{
/// <summary>
/// 运行时使用ILEmit动态创建THttpApi的代理类和代理类实例
/// </summary>
/// <typeparam name="THttpApi"></typeparam>
public sealed class ILEmitHttpApiActivator<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] THttpApi>
: IHttpApiActivator<THttpApi>
{
private readonly ApiActionInvoker[] actionInvokers;
private readonly Func<IHttpApiInterceptor, ApiActionInvoker[], THttpApi> activator;
/// <summary>
/// 运行时使用ILEmit动态创建THttpApi的代理类和代理类实例
/// </summary>
/// <param name="apiActionDescriptorProvider"></param>
/// <param name="actionInvokerProvider"></param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="NotSupportedException"></exception>
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072", Justification = "proxyType是运行时生成的")]
[RequiresDynamicCode("Calls System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)")]
public ILEmitHttpApiActivator(IApiActionDescriptorProvider apiActionDescriptorProvider, IApiActionInvokerProvider actionInvokerProvider)
{
var apiMethods = HttpApi.FindApiMethods(typeof(THttpApi));
this.actionInvokers = apiMethods
.Select(item => apiActionDescriptorProvider.CreateActionDescriptor(item, typeof(THttpApi)))
.Select(actionInvokerProvider.CreateActionInvoker)
.ToArray();
var proxyType = BuildProxyType(apiMethods);
this.activator = LambdaUtil.CreateCtorFunc<IHttpApiInterceptor, ApiActionInvoker[], THttpApi>(proxyType);
}
/// <summary>
/// 创建接口的实例
/// </summary>
/// <param name="apiInterceptor">接口拦截器</param>
/// <returns></returns>
public THttpApi CreateInstance(IHttpApiInterceptor apiInterceptor)
{
return this.activator.Invoke(apiInterceptor, this.actionInvokers);
}
/// <summary>
/// IHttpApiInterceptor的Intercept方法
/// </summary>
private static readonly MethodInfo interceptMethod = typeof(IHttpApiInterceptor).GetMethod(nameof(IHttpApiInterceptor.Intercept)) ?? throw new MissingMethodException(nameof(IHttpApiInterceptor.Intercept));
/// <summary>
/// 代理类型的构造器的参数类型
/// (IHttpApiInterceptor interceptor,ApiActionInvoker[] actionInvokers)
/// </summary>
private static readonly Type[] proxyTypeCtorArgTypes = [typeof(IHttpApiInterceptor), typeof(ApiActionInvoker[])];
/// <summary>
/// 创建IHttpApi代理类的类型
/// </summary>
/// <param name="apiMethods">接口的方法</param>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ProxyTypeCreateException"></exception>
/// <returns></returns>
[RequiresDynamicCode("Calls System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)")]
private static Type BuildProxyType(MethodInfo[] apiMethods)
{
// 接口的实现在动态程序集里,所以接口必须为 public 修饰才可以创建代理类并实现此接口
var interfaceType = typeof(THttpApi);
if (interfaceType.IsVisible == false)
{
var message = Resx.required_PublicInterface.Format(interfaceType);
throw new NotSupportedException(message);
}
var moduleName = Guid.NewGuid().ToString();
var assemblyName = new AssemblyName(Guid.NewGuid().ToString());
var module = AssemblyBuilder
.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
.DefineDynamicModule(moduleName);
var typeName = interfaceType.FullName ?? Guid.NewGuid().ToString();
var builder = module.DefineType(typeName, System.Reflection.TypeAttributes.Class);
builder.AddInterfaceImplementation(interfaceType);
var fieldApiInterceptor = BuildField(builder, "<>apiInterceptor", typeof(IHttpApiInterceptor));
var fieldActionInvokers = BuildField(builder, "<>actionInvokers", typeof(ApiActionInvoker[]));
BuildCtor(builder, fieldApiInterceptor, fieldActionInvokers);
BuildMethods(builder, apiMethods, fieldApiInterceptor, fieldActionInvokers);
var proxyType = builder.CreateType();
return proxyType ?? throw new ProxyTypeCreateException(interfaceType);
}
/// <summary>
/// 生成代理类型的字段
/// </summary>
/// <param name="builder">类型生成器</param>
/// <param name="fieldName">字段名称</param>
/// <param name="fieldType">字段类型</param>
/// <returns></returns>
private static FieldBuilder BuildField(TypeBuilder builder, string fieldName, Type fieldType)
{
const FieldAttributes filedAttribute = FieldAttributes.Private | FieldAttributes.InitOnly;
return builder.DefineField(fieldName, fieldType, filedAttribute);
}
/// <summary>
/// 生成代理类型的构造器
/// </summary>
/// <param name="builder">类型生成器</param>
/// <param name="fieldApiInterceptor">拦截器字段</param>
/// <param name="fieldActionInvokers">action执行器字段</param>
/// <returns></returns>
private static void BuildCtor(TypeBuilder builder, FieldBuilder fieldApiInterceptor, FieldBuilder fieldActionInvokers)
{
// .ctor(IHttpApiInterceptor apiInterceptor, ApiActionInvoker[] actionInvokers)
var ctor = builder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, proxyTypeCtorArgTypes);
var il = ctor.GetILGenerator();
// this.apiInterceptor = 第一个参数
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, fieldApiInterceptor);
// this.actionInvokers = 第二个参数
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Stfld, fieldActionInvokers);
il.Emit(OpCodes.Ret);
}
/// <summary>
/// 生成代理类型的接口实现方法
/// </summary>
/// <param name="builder">类型生成器</param>
/// <param name="actionMethods">接口的方法</param>
/// <param name="fieldApiInterceptor">拦截器字段</param>
/// <param name="fieldActionInvokers">action执行器字段</param>
private static void BuildMethods(TypeBuilder builder, MethodInfo[] actionMethods, FieldBuilder fieldApiInterceptor, FieldBuilder fieldActionInvokers)
{
// private final hidebysig newslot virtual
const MethodAttributes implementAttribute = MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;
for (var i = 0; i < actionMethods.Length; i++)
{
var actionMethod = actionMethods[i];
var actionParameters = actionMethod.GetParameters();
var parameterTypes = actionParameters.Select(p => p.ParameterType).ToArray();
var actionMethodName = $"{actionMethod.DeclaringType?.FullName}.{actionMethod.Name}";
var methodBuilder = builder.DefineMethod(actionMethodName, implementAttribute, CallingConventions.Standard | CallingConventions.HasThis, actionMethod.ReturnType, parameterTypes);
builder.DefineMethodOverride(methodBuilder, actionMethod);
var iL = methodBuilder.GetILGenerator();
// this.apiInterceptor
iL.Emit(OpCodes.Ldarg_0);
iL.Emit(OpCodes.Ldfld, fieldApiInterceptor);
// this.actionInvokers[i]
iL.Emit(OpCodes.Ldarg_0);
iL.Emit(OpCodes.Ldfld, fieldActionInvokers);
iL.Emit(OpCodes.Ldc_I4, i);
iL.Emit(OpCodes.Ldelem_Ref);
// var arguments = new object[parameters.Length]
var arguments = iL.DeclareLocal(typeof(object[]));
iL.Emit(OpCodes.Ldc_I4, actionParameters.Length);
iL.Emit(OpCodes.Newarr, typeof(object));
iL.Emit(OpCodes.Stloc, arguments);
for (var j = 0; j < actionParameters.Length; j++)
{
iL.Emit(OpCodes.Ldloc, arguments);
iL.Emit(OpCodes.Ldc_I4, j);
iL.Emit(OpCodes.Ldarg, j + 1);
var parameterType = parameterTypes[j];
if (parameterType.IsValueType || parameterType.IsGenericParameter)
{
iL.Emit(OpCodes.Box, parameterType);
}
iL.Emit(OpCodes.Stelem_Ref);
}
// 加载 arguments 参数
iL.Emit(OpCodes.Ldloc, arguments);
// Intercept(actionInvoker, arguments)
iL.Emit(OpCodes.Callvirt, interceptMethod);
if (actionMethod.ReturnType == typeof(void))
{
iL.Emit(OpCodes.Pop);
}
iL.Emit(OpCodes.Castclass, actionMethod.ReturnType);
iL.Emit(OpCodes.Ret);
}
}
}
}