-
-
Notifications
You must be signed in to change notification settings - Fork 833
/
ConstructorParameterBinding.cs
190 lines (168 loc) · 8.13 KB
/
ConstructorParameterBinding.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
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// http://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
#if DNX451 || DNXCORE50
using System.Collections.Concurrent;
#endif
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using Autofac.Util;
namespace Autofac.Core.Activators.Reflection
{
/// <summary>
/// Binds a constructor to the parameters that will be used when it is invoked.
/// </summary>
public class ConstructorParameterBinding
{
readonly ConstructorInfo _ci;
readonly Func<object>[] _valueRetrievers;
#if DNX451 || DNXCORE50
readonly static ConcurrentDictionary<ConstructorInfo, Func<object[], object>> _constructorInvokers = new ConcurrentDictionary<ConstructorInfo, Func<object[], object>>();
#else
readonly static SafeDictionary<ConstructorInfo, Func<object[], object>> _constructorInvokers = new SafeDictionary<ConstructorInfo, Func<object[], object>>();
#endif
// We really need to report all non-bindable parameters, howevers some refactoring
// will be necessary before this is possible. Adding this now to ease the
// pain of working with the preview builds.
readonly ParameterInfo _firstNonBindableParameter;
/// <summary>
/// The constructor on the target type. The actual constructor used
/// might differ, e.g. if using a dynamic proxy.
/// </summary>
public ConstructorInfo TargetConstructor => _ci;
/// <summary>
/// True if the binding is valid.
/// </summary>
public bool CanInstantiate { get; }
/// <summary>
/// Construct a new ConstructorParameterBinding.
/// </summary>
/// <param name="ci">ConstructorInfo to bind.</param>
/// <param name="availableParameters">Available parameters.</param>
/// <param name="context">Context in which to construct instance.</param>
public ConstructorParameterBinding(
ConstructorInfo ci,
IEnumerable<Parameter> availableParameters,
IComponentContext context)
{
if (ci == null) throw new ArgumentNullException(nameof(ci));
if (availableParameters == null) throw new ArgumentNullException(nameof(availableParameters));
if (context == null) throw new ArgumentNullException(nameof(context));
CanInstantiate = true;
_ci = ci;
var parameters = ci.GetParameters();
_valueRetrievers = new Func<object>[parameters.Length];
for (int i = 0; i < parameters.Length; ++i)
{
var pi = parameters[i];
bool foundValue = false;
foreach (var param in availableParameters)
{
Func<object> valueRetriever;
if (param.CanSupplyValue(pi, context, out valueRetriever))
{
_valueRetrievers[i] = valueRetriever;
foundValue = true;
break;
}
}
if (!foundValue)
{
CanInstantiate = false;
_firstNonBindableParameter = pi;
break;
}
}
}
/// <summary>
/// Invoke the constructor with the parameter bindings.
/// </summary>
/// <returns>The constructed instance.</returns>
public object Instantiate()
{
if (!CanInstantiate)
throw new InvalidOperationException(ConstructorParameterBindingResources.CannotInstantitate);
var values = new object[_valueRetrievers.Length];
for (var i = 0; i < _valueRetrievers.Length; ++i)
values[i] = _valueRetrievers[i]();
Func<object[], object> constructorInvoker;
if (!_constructorInvokers.TryGetValue(TargetConstructor, out constructorInvoker))
{
constructorInvoker = GetConstructorInvoker(TargetConstructor);
_constructorInvokers[TargetConstructor] = constructorInvoker;
}
try
{
return constructorInvoker(values);
}
catch (TargetInvocationException ex)
{
throw new DependencyResolutionException(
string.Format(CultureInfo.CurrentCulture, ConstructorParameterBindingResources.ExceptionDuringInstantiation, TargetConstructor, TargetConstructor.DeclaringType.Name), ex.InnerException);
}
catch (Exception ex)
{
throw new DependencyResolutionException(
string.Format(CultureInfo.CurrentCulture, ConstructorParameterBindingResources.ExceptionDuringInstantiation, TargetConstructor, TargetConstructor.DeclaringType.Name), ex);
}
}
/// <summary>
/// Describes the constructor parameter binding.
/// </summary>
public string Description => CanInstantiate
? string.Format(CultureInfo.CurrentCulture, ConstructorParameterBindingResources.BoundConstructor, _ci)
: string.Format(CultureInfo.CurrentCulture, ConstructorParameterBindingResources.NonBindableConstructor, _ci, _firstNonBindableParameter);
///<summary>Returns a System.String that represents the current System.Object.</summary>
///<returns>A System.String that represents the current System.Object.</returns>
public override string ToString()
{
return Description;
}
static Func<object[], object> GetConstructorInvoker(ConstructorInfo constructorInfo)
{
var paramsInfo = constructorInfo.GetParameters();
var parametersExpression = Expression.Parameter(typeof(object[]), "args");
var argumentsExpression = new Expression[paramsInfo.Length];
for (int paramIndex = 0; paramIndex < paramsInfo.Length; paramIndex++)
{
var indexExpression = Expression.Constant(paramIndex);
var parameterType = paramsInfo[paramIndex].ParameterType;
var parameterIndexExpression = Expression.ArrayIndex(parametersExpression, indexExpression);
var convertExpression = Expression.Convert(parameterIndexExpression, parameterType);
argumentsExpression[paramIndex] = convertExpression;
if (!parameterType.GetTypeInfo().IsValueType) continue;
var nullConditionExpression = Expression.Equal(
parameterIndexExpression, Expression.Constant(null));
argumentsExpression[paramIndex] = Expression.Condition(
nullConditionExpression, Expression.Default(parameterType), convertExpression);
}
var newExpression = Expression.New(constructorInfo, argumentsExpression);
var lambdaExpression = Expression.Lambda<Func<object[], object>>(newExpression, parametersExpression);
return lambdaExpression.Compile();
}
}
}