forked from castleproject/Windsor
/
DefaultComponentActivator.cs
363 lines (324 loc) · 10.2 KB
/
DefaultComponentActivator.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
// Copyright 2004-2022 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Castle.MicroKernel.ComponentActivator
{
using System;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
#if FEATURE_REMOTING
using System.Security.Permissions;
#endif
using Castle.Core;
using Castle.Core.Internal;
using Castle.DynamicProxy;
using Castle.MicroKernel.Context;
#if FEATURE_SECURITY_PERMISSIONS
using Castle.Windsor.Compatibility;
#endif
/// <summary>
/// Standard implementation of <see cref = "IComponentActivator" />. Handles the selection of the best constructor, fills the writable properties the component exposes, run the commission and
/// decommission lifecycles, etc.
/// </summary>
/// <remarks>
/// Custom implementors can just override the <c>CreateInstance</c> method. Please note however that the activator is responsible for the proxy creation when needed.
/// </remarks>
[Serializable]
public class DefaultComponentActivator : AbstractComponentActivator
{
internal const string InstanceStash = "castle.component-activator-instance";
#if FEATURE_REMOTING
private readonly bool useFastCreateInstance;
#endif
/// <summary>
/// Initializes a new instance of the <see cref = "DefaultComponentActivator" /> class.
/// </summary>
/// <param name = "model"> </param>
/// <param name = "kernel"> </param>
/// <param name = "onCreation"> </param>
/// <param name = "onDestruction"> </param>
public DefaultComponentActivator(ComponentModel model, IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
: base(model, kernel, onCreation, onDestruction)
{
#if FEATURE_REMOTING
useFastCreateInstance = !model.Implementation.IsContextful && new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).IsGranted();
#endif
}
protected override object InternalCreate(CreationContext context)
{
var instance = Instantiate(context);
context.SetContextualProperty(InstanceStash, instance);
SetUpProperties(instance, context);
ApplyCommissionConcerns(instance);
return instance;
}
protected override void InternalDestroy(object instance)
{
ApplyDecommissionConcerns(instance);
}
protected virtual object Instantiate(CreationContext context)
{
var candidate = SelectEligibleConstructor(context);
var arguments = CreateConstructorArguments(candidate, context);
return CreateInstance(context, candidate, arguments);
}
protected virtual object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
{
object instance = null;
var implType = Model.Implementation;
var createProxy = Kernel.ProxyFactory.ShouldCreateProxy(Model);
if (createProxy == false && Model.Implementation.GetTypeInfo().IsAbstract)
{
throw new ComponentRegistrationException(
string.Format(
"Type {0} is abstract.{2} As such, it is not possible to instantiate it as implementation of service '{1}'. Did you forget to proxy it?",
Model.Implementation.FullName,
Model.Name,
Environment.NewLine));
}
var createInstance = true;
if (createProxy)
{
createInstance = Kernel.ProxyFactory.RequiresTargetInstance(Kernel, Model);
}
if (createInstance)
{
instance = CreateInstanceCore(constructor, arguments, implType);
}
if (createProxy)
{
try
{
instance = Kernel.ProxyFactory.Create(Kernel, instance, Model, context, arguments);
}
catch (Exception ex)
{
if (arguments != null)
{
foreach (var argument in arguments)
{
Kernel.ReleaseComponent(argument);
}
}
throw new ComponentActivatorException("ComponentActivator: could not proxy " + Model.Implementation.FullName, ex, Model);
}
}
return instance;
}
protected object CreateInstanceCore(ConstructorCandidate constructor, object[] arguments, Type implType)
{
object instance;
try
{
#if FEATURE_REMOTING
if (useFastCreateInstance)
{
instance = FastCreateInstance(implType, arguments, constructor);
}
else
#endif
{
instance = implType.CreateInstance<object>(arguments);
}
}
catch (Exception ex)
{
if (arguments != null)
{
foreach (var argument in arguments)
{
Kernel.ReleaseComponent(argument);
}
}
if (ex is ComponentActivatorException)
{
throw;
}
throw new ComponentActivatorException(
"ComponentActivator: could not instantiate " + Model.Implementation.FullName, ex, Model);
}
return instance;
}
#if FEATURE_REMOTING
[SecuritySafeCritical]
private object FastCreateInstance(Type implType, object[] arguments, ConstructorCandidate constructor)
{
if (constructor == null || constructor.Constructor == null)
{
throw new ComponentActivatorException(
string.Format(
"Could not find a public constructor for type {0}.{1}" +
"Windsor by default cannot instantiate types that don't expose public constructors.{1}" +
"To expose the type as a service add public constructor, or use custom component activator.",
implType,
Environment.NewLine), Model);
}
var instance = FormatterServices.GetUninitializedObject(implType);
constructor.Constructor.Invoke(instance, arguments);
return instance;
}
#endif
protected virtual ConstructorCandidate SelectEligibleConstructor(CreationContext context)
{
if (Model.Constructors.Count == 0)
{
// This is required by some facilities
return null;
}
if (Model.Constructors.Count == 1)
{
return Model.Constructors[0];
}
ConstructorCandidate winnerCandidate = null;
var winnerPoints = 0;
foreach (var candidate in Model.Constructors)
{
int candidatePoints;
if (CheckCtorCandidate(candidate, context, out candidatePoints) == false)
{
continue;
}
if (BestScoreSoFar(candidatePoints, winnerPoints, winnerCandidate))
{
if (BestPossibleScore(candidate, candidatePoints))
{
//since the constructors are sorted greedier first, we know there's no way any other .ctor is going to beat us here
return candidate;
}
winnerCandidate = candidate;
winnerPoints = candidatePoints;
}
}
if (winnerCandidate == null)
{
throw new NoResolvableConstructorFoundException(Model.Implementation, Model);
}
return winnerCandidate;
}
private static bool BestScoreSoFar(int candidatePoints, int winnerPoints, ConstructorCandidate winnerCandidate)
{
return winnerCandidate == null || winnerPoints < candidatePoints;
}
private static bool BestPossibleScore(ConstructorCandidate candidate, int candidatePoints)
{
return candidatePoints == candidate.Dependencies.Length*100;
}
private bool CheckCtorCandidate(ConstructorCandidate candidate, CreationContext context, out int candidatePoints)
{
candidatePoints = 0;
foreach (var dependency in candidate.Dependencies)
{
if (CanSatisfyDependency(context, dependency))
{
candidatePoints += 100;
}
else if (dependency.HasDefaultValue)
{
candidatePoints += 1;
}
else
{
candidatePoints = 0;
return false;
}
}
return true;
}
protected virtual bool CanSatisfyDependency(CreationContext context, DependencyModel dependency)
{
return Kernel.Resolver.CanResolve(context, context.Handler, Model, dependency);
}
protected virtual object[] CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context)
{
if (constructor == null)
{
return null;
}
var dependencyCount = constructor.Dependencies.Length;
if (dependencyCount == 0)
{
return null;
}
var arguments = new object[dependencyCount];
try
{
for (var i = 0; i < dependencyCount; i++)
{
arguments[i] = Kernel.Resolver.Resolve(context, context.Handler, Model, constructor.Dependencies[i]);
}
return arguments;
}
catch
{
foreach (var argument in arguments)
{
Kernel.ReleaseComponent(argument);
}
throw;
}
}
protected virtual void SetUpProperties(object instance, CreationContext context)
{
instance = ProxyUtil.GetUnproxiedInstance(instance);
var resolver = Kernel.Resolver;
foreach (var property in Model.Properties)
{
var value = ObtainPropertyValue(context, property, resolver);
if (value == null)
{
continue;
}
var setMethod = property.Property.GetSetMethod();
try
{
setMethod.Invoke(instance, new[] { value });
}
catch (Exception ex)
{
var message =
String.Format(
"Error setting property {1}.{0} in component {2}. See inner exception for more information.{4}" +
"If you don't want Windsor to set this property you can do it by either decorating it with {3} or via registration API.{4}" +
"Alternatively consider making the setter non-public.",
property.Property.Name,
instance.GetType().Name,
Model.Name,
typeof(DoNotWireAttribute).Name,
Environment.NewLine);
throw new ComponentActivatorException(message, ex, Model);
}
}
}
private object ObtainPropertyValue(CreationContext context, PropertySet property, IDependencyResolver resolver)
{
if (property.Dependency.IsOptional == false ||
resolver.CanResolve(context, context.Handler, Model, property.Dependency))
{
try
{
return resolver.Resolve(context, context.Handler, Model, property.Dependency);
}
catch (Exception e)
{
if (property.Dependency.IsOptional == false)
{
throw;
}
Kernel.Logger.Warn(string.Format("Exception when resolving optional dependency {0} on component {1}.", property.Dependency, Model.Name), e);
}
}
return null;
}
}
}