-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActivatorUtilities.cs
412 lines (358 loc) · 17.4 KB
/
ActivatorUtilities.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.ExceptionServices;
using ApacheTech.Common.Extensions.Reflection;
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
namespace ApacheTech.Common.DependencyInjection.Abstractions
{
/// <summary>
/// Helper code for the various activator services.
/// </summary>
public static class ActivatorUtilities
{
private static readonly MethodInfo GetServiceInfo =
GetMethodInfo<Func<IServiceProvider, Type, Type, bool, object>>((sp, t, r, c) => GetService(sp, t, r, c));
/// <summary>
/// </summary>
/// <param name="provider">The service provider used to resolve dependencies</param>
/// <param name="instanceType">The type to activate</param>
/// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param>
/// <returns>An activated object of type instanceType</returns>
public static object CreateInstance(IServiceProvider provider, Type instanceType, params object[] parameters)
{
var bestLength = -1;
var seenPreferred = false;
ConstructorMatcher bestMatcher = null;
if (!instanceType.GetTypeInfo().IsAbstract)
{
foreach (var constructor in instanceType
.GetTypeInfo()
.DeclaredConstructors
.Where(c => !c.IsStatic && c.IsPublic))
{
var matcher = new ConstructorMatcher(constructor);
var isPreferred = constructor.HasCustomAttribute<ActivatorUtilitiesConstructor>();
var length = matcher.Match(parameters);
if (isPreferred)
{
if (seenPreferred)
{
ThrowMultipleConstructorsMarkedWithAttributeException();
}
if (length == -1)
{
ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
}
}
if (isPreferred || bestLength < length)
{
bestLength = length;
bestMatcher = matcher;
}
seenPreferred |= isPreferred;
}
}
if (bestMatcher != null) return bestMatcher.CreateInstance(provider);
var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.";
throw new InvalidOperationException(message);
}
/// <summary>
/// Create a delegate that will instantiate a type with constructor arguments provided directly
/// and/or from an <see cref="IServiceProvider"/>.
/// </summary>
/// <param name="instanceType">The type to activate</param>
/// <param name="argumentTypes">
/// The types of objects, in order, that will be passed to the returned function as its second parameter
/// </param>
/// <returns>
/// A factory that will instantiate instanceType using an <see cref="IServiceProvider"/>
/// and an argument array containing objects matching the types defined in argumentTypes
/// </returns>
public static ObjectFactory CreateFactory(Type instanceType, Type[] argumentTypes)
{
FindApplicableConstructor(instanceType, argumentTypes, out var constructor, out var parameterMap);
var provider = Expression.Parameter(typeof(IServiceProvider), "provider");
var argumentArray = Expression.Parameter(typeof(object[]), "argumentArray");
var factoryExpressionBody = BuildFactoryExpression(constructor, parameterMap, provider, argumentArray);
var factoryLambda = Expression.Lambda<Func<IServiceProvider, object[], object>>(
factoryExpressionBody, provider, argumentArray);
var result = factoryLambda.Compile();
return result.Invoke;
}
/// <summary>
/// Instantiate a type with constructor arguments provided directly and/or from an <see cref="IServiceProvider"/>.
/// </summary>
/// <typeparam name="T">The type to activate</typeparam>
/// <param name="provider">The service provider used to resolve dependencies</param>
/// <param name="parameters">Constructor arguments not provided by the <paramref name="provider"/>.</param>
/// <returns>An activated object of type T</returns>
public static T CreateInstance<T>(IServiceProvider provider, params object[] parameters)
{
return (T)CreateInstance(provider, typeof(T), parameters);
}
/// <summary>
/// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly.
/// </summary>
/// <typeparam name="T">The type of the service</typeparam>
/// <param name="provider">The service provider used to resolve dependencies</param>
/// <returns>The resolved service or created instance</returns>
public static T GetServiceOrCreateInstance<T>(IServiceProvider provider)
{
return (T)GetServiceOrCreateInstance(provider, typeof(T));
}
/// <summary>
/// Retrieve an instance of the given type from the service provider. If one is not found then instantiate it directly.
/// </summary>
/// <param name="provider">The service provider</param>
/// <param name="type">The type of the service</param>
/// <returns>The resolved service or created instance</returns>
public static object GetServiceOrCreateInstance(IServiceProvider provider, Type type)
{
return provider.GetService(type) ?? CreateInstance(provider, type);
}
private static MethodInfo GetMethodInfo<T>(Expression<T> expr)
{
var mc = (MethodCallExpression)expr.Body;
return mc.Method;
}
private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
{
var service = sp.GetService(type);
if (service == null && !isDefaultParameterRequired)
{
var message = $"Unable to resolve service for type '{type}' while attempting to activate '{requiredBy}'.";
throw new InvalidOperationException(message);
}
return service;
}
private static Expression BuildFactoryExpression(
ConstructorInfo constructor,
int?[] parameterMap,
Expression serviceProvider,
Expression factoryArgumentArray)
{
var constructorParameters = constructor.GetParameters();
var constructorArguments = new Expression[constructorParameters.Length];
for (var i = 0; i < constructorParameters.Length; i++)
{
var constructorParameter = constructorParameters[i];
var parameterType = constructorParameter.ParameterType;
var hasDefaultValue = constructorParameter.TryGetDefaultValue(out var defaultValue);
if (parameterMap[i] != null)
{
constructorArguments[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i]));
}
else
{
var parameterTypeExpression = new [] { serviceProvider,
Expression.Constant(parameterType, typeof(Type)),
Expression.Constant(constructor.DeclaringType, typeof(Type)),
Expression.Constant(hasDefaultValue) };
constructorArguments[i] = Expression.Call(GetServiceInfo, parameterTypeExpression);
}
// Support optional constructor arguments by passing in the default value
// when the argument would otherwise be null.
if (hasDefaultValue)
{
var defaultValueExpression = Expression.Constant(defaultValue);
constructorArguments[i] = Expression.Coalesce(constructorArguments[i], defaultValueExpression);
}
constructorArguments[i] = Expression.Convert(constructorArguments[i], parameterType);
}
return Expression.New(constructor, constructorArguments);
}
private static void FindApplicableConstructor(
Type instanceType,
Type[] argumentTypes,
out ConstructorInfo matchingConstructor,
out int?[] parameterMap)
{
matchingConstructor = null;
parameterMap = null;
if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref matchingConstructor, ref parameterMap) &&
!TryFindMatchingConstructor(instanceType, argumentTypes, ref matchingConstructor, ref parameterMap))
{
var message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.";
throw new InvalidOperationException(message);
}
}
// Tries to find constructor based on provided argument types
private static bool TryFindMatchingConstructor(
Type instanceType,
Type[] argumentTypes,
ref ConstructorInfo matchingConstructor,
ref int?[] parameterMap)
{
foreach (var constructor in instanceType.GetTypeInfo().DeclaredConstructors)
{
if (constructor.IsStatic || !constructor.IsPublic)
{
continue;
}
if (!TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out var tempParameterMap))
continue;
if (matchingConstructor != null)
{
throw new InvalidOperationException($"Multiple constructors accepting all given argument types have been found in type '{instanceType}'. There should only be one applicable constructor.");
}
matchingConstructor = constructor;
parameterMap = tempParameterMap;
}
return matchingConstructor != null;
}
// Tries to find constructor marked with ActivatorUtilitiesConstructorAttribute
private static bool TryFindPreferredConstructor(
Type instanceType,
Type[] argumentTypes,
ref ConstructorInfo matchingConstructor,
ref int?[] parameterMap)
{
var seenPreferred = false;
foreach (var constructor in instanceType.GetTypeInfo().DeclaredConstructors)
{
if (constructor.IsStatic || !constructor.IsPublic)
{
continue;
}
if (!constructor.HasCustomAttribute<ActivatorUtilitiesConstructor>()) continue;
if (seenPreferred)
{
ThrowMultipleConstructorsMarkedWithAttributeException();
}
if (!TryCreateParameterMap(constructor.GetParameters(), argumentTypes, out var tempParameterMap))
{
ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
}
matchingConstructor = constructor;
parameterMap = tempParameterMap;
seenPreferred = true;
}
return matchingConstructor != null;
}
// Creates an injectable parameterMap from givenParameterTypes to assignable constructorParameters.
// Returns true if each given parameter type is assignable to a unique; otherwise, false.
private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap)
{
parameterMap = new int?[constructorParameters.Length];
for (var i = 0; i < argumentTypes.Length; i++)
{
var foundMatch = false;
var givenParameter = argumentTypes[i].GetTypeInfo();
for (var j = 0; j < constructorParameters.Length; j++)
{
if (parameterMap[j] != null)
{
// This ctor parameter has already been matched
continue;
}
if (constructorParameters[j].ParameterType.GetTypeInfo().IsAssignableFrom(givenParameter))
{
foundMatch = true;
parameterMap[j] = i;
break;
}
}
if (!foundMatch)
{
return false;
}
}
return true;
}
private class ConstructorMatcher
{
private readonly ConstructorInfo _constructor;
private readonly ParameterInfo[] _parameters;
private readonly object[] _parameterValues;
private readonly bool[] _parameterValuesSet;
public ConstructorMatcher(ConstructorInfo constructor)
{
_constructor = constructor;
_parameters = _constructor.GetParameters();
_parameterValuesSet = new bool[_parameters.Length];
_parameterValues = new object[_parameters.Length];
}
public int Match(object[] givenParameters)
{
var applyIndexStart = 0;
var applyExactLength = 0;
for (var givenIndex = 0; givenIndex != givenParameters.Length; givenIndex++)
{
var givenType = givenParameters[givenIndex]?.GetType().GetTypeInfo();
var givenMatched = false;
for (var applyIndex = applyIndexStart; givenMatched == false && applyIndex != _parameters.Length; ++applyIndex)
{
if (_parameterValuesSet[applyIndex] == false &&
_parameters[applyIndex].ParameterType.GetTypeInfo().IsAssignableFrom(givenType))
{
givenMatched = true;
_parameterValuesSet[applyIndex] = true;
_parameterValues[applyIndex] = givenParameters[givenIndex];
if (applyIndexStart == applyIndex)
{
applyIndexStart++;
if (applyIndex == givenIndex)
{
applyExactLength = applyIndex;
}
}
}
}
if (givenMatched == false)
{
return -1;
}
}
return applyExactLength;
}
public object CreateInstance(IServiceProvider provider)
{
for (var index = 0; index != _parameters.Length; index++)
{
if (_parameterValuesSet[index] == false)
{
var value = provider.GetService(_parameters[index].ParameterType);
if (value == null)
{
if (!_parameters[index].TryGetDefaultValue(out var defaultValue))
{
throw new InvalidOperationException($"Unable to resolve service for type '{_parameters[index].ParameterType}' while attempting to activate '{_constructor.DeclaringType}'.");
}
else
{
_parameterValues[index] = defaultValue;
}
}
else
{
_parameterValues[index] = value;
}
}
}
try
{
return _constructor.Invoke(_parameterValues);
}
catch (TargetInvocationException ex)
{
if (ex.InnerException is not null)
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
// The above line will always throw, but the compiler requires we throw explicitly.
throw;
}
}
}
private static void ThrowMultipleConstructorsMarkedWithAttributeException()
{
throw new InvalidOperationException("Multiple constructors were marked with a service-based constructor attribute.");
}
private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments()
{
throw new InvalidOperationException("Constructor marked with a service-based constructor attribute does not accept all given argument types.");
}
}
}