forked from dsuryd/dotNetify-Blazor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypeProxy.cs
233 lines (197 loc) · 6.64 KB
/
TypeProxy.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
Copyright 2020 Dicky Suryadi
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading.Tasks;
using Castle.DynamicProxy;
[assembly: InternalsVisibleTo("DotNetify.Blazor.UnitTests")]
namespace DotNetify.Blazor
{
public class TypeProxyException : Exception
{
public TypeProxyException(string message) : base(message)
{
}
}
public abstract class BaseObject : IVMState
{
[JsonIgnore]
public IVMProxy VMProxy { get; set; }
}
internal class ProxyTypeInfoResolver : DefaultJsonTypeInfoResolver
{
public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
{
JsonTypeInfo typeInfo = base.GetTypeInfo(type, options);
if (typeInfo.Kind == JsonTypeInfoKind.Object && typeInfo.Type.IsInterface)
{
typeInfo.CreateObject = () => TypeProxy.Create(type);
}
return typeInfo;
}
}
internal class ProxyInterceptor : IInterceptor
{
private readonly Dictionary<string, object> _propValues = new Dictionary<string, object>();
private readonly PropertyInfo[] _interfaceProperties;
private enum ReservedMethod
{
Dispatch,
Dispose,
DispatchAsync,
DisposeAsync
}
public ProxyInterceptor(Type interfaceType)
{
_interfaceProperties = interfaceType.GetProperties();
}
public void Intercept(IInvocation invocation)
{
if (IsProperty(invocation))
{
HandleProperty(invocation);
}
else
{
HandleMethod(invocation);
}
}
private bool IsProperty(IInvocation invocation)
{
var method = invocation.Method;
return _interfaceProperties.Any(prop => prop.GetAccessors().Contains(method));
}
private bool IsAsyncMethod(IInvocation invocation)
{
var method = invocation.Method;
var returnType = method.ReturnType;
return typeof(Task).IsAssignableFrom(returnType);
}
private void HandleProperty(IInvocation invocation)
{
var method = invocation.Method;
var property = _interfaceProperties.First(prop => prop.GetAccessors().Contains(method));
if (invocation.Method == property.SetMethod)
{
HandleSetProperty(invocation, property);
}
else
{
HandleGetProperty(invocation, property);
}
}
private void HandleSetProperty(IInvocation invocation, PropertyInfo property)
{
var value = invocation.Arguments.First();
_propValues[property.Name] = value;
var hasWatchAttribute = property.GetCustomAttribute<WatchAttribute>() != null;
if (hasWatchAttribute)
{
var vmProxy = GetVMProxy(invocation);
vmProxy.DispatchAsync(property.Name, value);
}
}
private void HandleGetProperty(IInvocation invocation, PropertyInfo property)
{
if (!_propValues.ContainsKey(property.Name))
{
invocation.ReturnValue = GetDefaultPropertyValue(property);
}
else
{
invocation.ReturnValue = _propValues[property.Name];
}
}
private void HandleMethod(IInvocation invocation)
{
var vmProxy = GetVMProxy(invocation);
var methodName = invocation.Method.Name;
Task returnTask;
if (methodName == nameof(ReservedMethod.Dispose) || methodName == nameof(ReservedMethod.DisposeAsync))
{
returnTask = vmProxy.DisposeAsync();
}
else if (methodName == nameof(ReservedMethod.Dispatch) || methodName == nameof(ReservedMethod.DispatchAsync))
{
var value = invocation.Arguments.FirstOrDefault();
if (value is Dictionary<string, object> properties)
{
returnTask = vmProxy.DispatchAsync(properties);
}
else
{
throw new TypeProxyException("'Dispatch' is a reserved method that requires a single argument of type Dictionary<string, object>.");
}
}
else
{
var value = invocation.Arguments.FirstOrDefault();
returnTask = vmProxy.DispatchAsync(methodName, value);
}
if (IsAsyncMethod(invocation))
{
invocation.ReturnValue = returnTask;
}
}
private IVMProxy GetVMProxy(IInvocation invocation)
{
var vmProxy = ((BaseObject)invocation.Proxy).VMProxy;
if (vmProxy == null)
{
throw new TypeProxyException("VMProxy has not been provided");
}
return vmProxy;
}
private object GetDefaultPropertyValue(PropertyInfo propertyInfo)
{
return GetType()
.GetMethod(nameof(GetDefaultGeneric), BindingFlags.Instance | BindingFlags.NonPublic)!
.MakeGenericMethod(propertyInfo.PropertyType)
.Invoke(this, null);
}
private TValue GetDefaultGeneric<TValue>()
{
return default;
}
}
public static class TypeProxy
{
private static readonly ProxyGenerator Generator = new ProxyGenerator();
public static T Create<T>()
{
return (T)Create(typeof(T));
}
public static object Create(Type type)
{
var proxy = Generator.CreateInterfaceProxyWithoutTarget(type, new ProxyGenerationOptions()
{
BaseTypeForInterfaceProxy = typeof(BaseObject)
}, new ProxyInterceptor(type));
return proxy;
}
public static T Deserialize<T>(string data)
{
var jsonSettings = new JsonSerializerOptions()
{
TypeInfoResolver = new ProxyTypeInfoResolver()
};
return JsonSerializer.Deserialize<T>(data, jsonSettings);
}
}
}