-
-
Notifications
You must be signed in to change notification settings - Fork 456
/
CacheReflectionHelper.cs
331 lines (270 loc) · 12.4 KB
/
CacheReflectionHelper.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using CacheManager.Core.Logging;
using static CacheManager.Core.Utility.Guard;
namespace CacheManager.Core.Internal
{
internal static class CacheReflectionHelper
{
internal static ILoggerFactory CreateLoggerFactory(ICacheManagerConfiguration configuration)
{
NotNull(configuration, nameof(configuration));
if (configuration.LoggerFactoryType == null)
{
return new NullLoggerFactory();
}
CheckImplements<ILoggerFactory>(configuration.LoggerFactoryType);
var args = new object[] { configuration };
if (configuration.LoggerFactoryTypeArguments != null)
{
args = configuration.LoggerFactoryTypeArguments.Concat(args).ToArray();
}
return (ILoggerFactory)CreateInstance(configuration.LoggerFactoryType, args);
}
internal static ICacheSerializer CreateSerializer(ICacheManagerConfiguration configuration, ILoggerFactory loggerFactory)
{
NotNull(configuration, nameof(configuration));
NotNull(loggerFactory, nameof(loggerFactory));
#if !NETSTANDARD2
if (configuration.SerializerType == null)
{
return new BinaryCacheSerializer();
}
#endif
if (configuration.SerializerType != null)
{
CheckImplements<ICacheSerializer>(configuration.SerializerType);
var args = new object[] { configuration, loggerFactory };
if (configuration.SerializerTypeArguments != null)
{
args = configuration.SerializerTypeArguments.Concat(args).ToArray();
}
return (ICacheSerializer)CreateInstance(configuration.SerializerType, args);
}
return null;
}
internal static CacheBackplane CreateBackplane(ICacheManagerConfiguration configuration, ILoggerFactory loggerFactory)
{
NotNull(configuration, nameof(configuration));
NotNull(loggerFactory, nameof(loggerFactory));
if (configuration.BackplaneType != null)
{
if (!configuration.CacheHandleConfigurations.Any(p => p.IsBackplaneSource))
{
throw new InvalidOperationException(
"At least one cache handle must be marked as the backplane source if a backplane is defined via configuration.");
}
CheckExtends<CacheBackplane>(configuration.BackplaneType);
var args = new object[] { configuration, loggerFactory };
if (configuration.BackplaneTypeArguments != null)
{
args = configuration.BackplaneTypeArguments.Concat(args).ToArray();
}
return (CacheBackplane)CreateInstance(configuration.BackplaneType, args);
}
return null;
}
internal static ICollection<BaseCacheHandle<TCacheValue>> CreateCacheHandles<TCacheValue>(
BaseCacheManager<TCacheValue> manager,
ILoggerFactory loggerFactory,
ICacheSerializer serializer)
{
NotNull(manager, nameof(manager));
NotNull(loggerFactory, nameof(loggerFactory));
var logger = loggerFactory.CreateLogger(nameof(CacheReflectionHelper));
var managerConfiguration = manager.Configuration as ICacheManagerConfiguration;
var handles = new List<BaseCacheHandle<TCacheValue>>();
foreach (var handleConfiguration in managerConfiguration.CacheHandleConfigurations)
{
logger.LogInfo("Creating handle {0} of type {1}.", handleConfiguration.Name, handleConfiguration.HandleType);
var handleType = handleConfiguration.HandleType;
var requiresSerializer = false;
requiresSerializer = handleType.GetTypeInfo().CustomAttributes.Any(p => p.AttributeType == typeof(RequiresSerializerAttribute));
if (requiresSerializer && serializer == null)
{
throw new InvalidOperationException($"Cache handle {handleType.FullName} requires serialization of cached values but no serializer has been configured.");
}
Type instanceType = null;
ValidateCacheHandleGenericTypeArguments(handleType);
// if the configured type doesn't have a generic type definition ( <T> is not
// defined )
if (handleType.GetTypeInfo().IsGenericTypeDefinition)
{
instanceType = handleType.MakeGenericType(new Type[] { typeof(TCacheValue) });
}
else
{
instanceType = handleType;
}
var types = new List<object>(new object[] { loggerFactory, managerConfiguration, manager, handleConfiguration });
if (handleConfiguration.ConfigurationTypes.Length > 0)
{
types.AddRange(handleConfiguration.ConfigurationTypes);
}
if (serializer != null)
{
types.Add(serializer);
}
var instance = CreateInstance(instanceType, types.ToArray()) as BaseCacheHandle<TCacheValue>;
if (instance == null)
{
throw new InvalidOperationException("Couldn't initialize handle of type " + instanceType.FullName);
}
handles.Add(instance);
}
if (handles.Count == 0)
{
throw new InvalidOperationException("No cache handles defined.");
}
// validate backplane is the last handle in the cache manager (only if backplane is configured)
if (handles.Any(p => p.Configuration.IsBackplaneSource) && manager.Configuration.BackplaneType != null)
{
if (!handles.Last().Configuration.IsBackplaneSource)
{
throw new InvalidOperationException("The last cache handle should be the backplane source.");
}
}
return handles;
}
internal static object CreateInstance(Type instanceType, object[] knownInstances)
{
var constructors = instanceType.GetTypeInfo().DeclaredConstructors;
constructors = constructors
.Where(p => !p.IsStatic && p.IsPublic)
.OrderByDescending(p => p.GetParameters().Length)
.ToArray();
if (constructors.Count() == 0)
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "No matching public non static constructor found for type {0}.", instanceType.FullName));
}
var args = MatchArguments(constructors, knownInstances);
try
{
return Activator.CreateInstance(instanceType, args);
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Failed to initialize instance of type {0}.",
instanceType),
ex.InnerException);
}
throw new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Failed to initialize instance of type {0}.",
instanceType),
ex);
}
}
private static object[] MatchArguments(IEnumerable<ConstructorInfo> constructors, object[] instances)
{
ParameterInfo lastParamMiss = null;
ConstructorInfo lastCtor = null;
foreach (var constructor in constructors)
{
lastCtor = constructor;
var args = new List<object>();
var parameters = constructor.GetParameters();
var instancesCopy = new List<object>(instances);
foreach (var param in parameters)
{
var paramValue = instancesCopy
.Where(p => p != null)
.FirstOrDefault(p => param.ParameterType.GetTypeInfo().IsAssignableFrom(p.GetType().GetTypeInfo()));
if (paramValue == null)
{
lastParamMiss = param;
break;
}
// fixing #112 by not looking at the same instance again which was already added to the args
instancesCopy.Remove(paramValue);
args.Add(paramValue);
}
if (parameters.Length == args.Count)
{
return args.ToArray();
}
}
if (constructors.Any(p => p.GetParameters().Length == 0))
{
// no match found, will try empty ctor
return new object[] { };
}
// give more detailed error of what failed
if (lastCtor != null && lastParamMiss != null)
{
var ctorTypes = string.Join(", ", lastCtor.GetParameters().Select(p => p.ParameterType.Name).ToArray());
throw new InvalidOperationException(
$"Could not find a matching constructor for type '{lastCtor.DeclaringType.Name}'. Trying to match [{ctorTypes}] but missing {lastParamMiss.ParameterType.Name}");
}
throw new InvalidOperationException(
$"Could not find a matching or empty constructor for type '{lastCtor.DeclaringType.Name}'.");
}
private static IEnumerable<Type> GetGenericBaseTypes(this Type type)
{
var baseType = type.GetTypeInfo().BaseType;
if (baseType == null || !baseType.GetTypeInfo().IsGenericType)
{
return Enumerable.Empty<Type>();
}
var genericBaseType = baseType.GetTypeInfo().IsGenericTypeDefinition ? baseType : baseType.GetGenericTypeDefinition();
return Enumerable.Repeat(genericBaseType, 1)
.Concat(baseType.GetGenericBaseTypes());
}
private static void ValidateCacheHandleGenericTypeArguments(Type handle)
{
// not really needed due to the generic type from callees being restricted.
if (!handle.GetGenericBaseTypes().Any(p => p == typeof(BaseCacheHandle<>)))
{
throw new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Configured cache handle does not implement base cache handle [{0}].",
handle.ToString()));
}
if (handle.IsGenericType && !handle.IsGenericTypeDefinition)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Cache handle type [{0}] should not have any generic arguments defined.",
handle.ToString()));
}
}
private static void CheckImplements<TValid>(Type type)
{
var interfaces = type.GetInterfaces();
Ensure(
interfaces.Any(p => p == typeof(TValid)),
"Type must implement {0}, but {1} does not.",
typeof(TValid).Name,
type.FullName);
}
private static void CheckExtends<TValid>(Type type)
{
var baseType = type.BaseType;
while (baseType != typeof(object))
{
if (baseType == typeof(TValid))
{
return;
}
baseType = type.BaseType;
}
throw new InvalidOperationException(
string.Format(
"Type {0} does not extend from {1}.",
type.FullName,
typeof(TValid).Name));
}
}
}