-
Notifications
You must be signed in to change notification settings - Fork 458
/
Copy pathDefaultDependencyResolver.cs
465 lines (415 loc) · 16.7 KB
/
DefaultDependencyResolver.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// Copyright 2004-2014 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.Resolvers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Castle.Core;
using Castle.Core.Internal;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Handlers;
using Castle.MicroKernel.SubSystems.Conversion;
/// <summary>Default implementation for <see cref = "IDependencyResolver" />. This implementation is quite simple, but still should be useful for 99% of situations.</summary>
[Serializable]
public class DefaultDependencyResolver : IDependencyResolver
{
private readonly IList<ISubDependencyResolver> subResolvers = new List<ISubDependencyResolver>();
private ITypeConverter converter;
private DependencyDelegate dependencyResolvingDelegate;
private IKernelInternal kernel;
/// <summary>Registers a sub resolver instance</summary>
/// <param name = "subResolver">The subresolver instance</param>
public void AddSubResolver(ISubDependencyResolver subResolver)
{
if (subResolver == null)
{
throw new ArgumentNullException("subResolver");
}
subResolvers.Add(subResolver);
}
/// <summary>Initializes this instance with the specified dependency delegate.</summary>
/// <param name = "kernel">kernel</param>
/// <param name = "dependencyDelegate">The dependency delegate.</param>
public void Initialize(IKernelInternal kernel, DependencyDelegate dependencyDelegate)
{
this.kernel = kernel;
converter = kernel.GetConversionManager();
dependencyResolvingDelegate = dependencyDelegate;
}
/// <summary>Unregisters a sub resolver instance previously registered</summary>
/// <param name = "subResolver">The subresolver instance</param>
public void RemoveSubResolver(ISubDependencyResolver subResolver)
{
subResolvers.Remove(subResolver);
}
/// <summary>Returns true if the resolver is able to satisfy the specified dependency.</summary>
/// <param name = "context">Creation context, which is a resolver itself</param>
/// <param name = "contextHandlerResolver">Parent resolver</param>
/// <param name = "model">Model of the component that is requesting the dependency</param>
/// <param name = "dependency">The dependency model</param>
/// <returns>
/// <c>true</c>
/// if the dependency can be satisfied
/// </returns>
public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
// 1 - check for the dependency on CreationContext, if present
if (CanResolveFromContext(context, contextHandlerResolver, model, dependency))
{
return true;
}
// 2 - check with the model's handler, if not the same as the parent resolver
if (CanResolveFromHandler(context, contextHandlerResolver, model, dependency))
{
return true;
}
// 3 - check within parent resolver, if present
if (CanResolveFromContextHandlerResolver(context, contextHandlerResolver, model, dependency))
{
return true;
}
// 4 - check within subresolvers
if (CanResolveFromSubResolvers(context, contextHandlerResolver, model, dependency))
{
return true;
}
// 5 - normal flow, checking against the kernel
return CanResolveFromKernel(context, model, dependency);
}
/// <summary>Try to resolve the dependency by checking the parameters in the model or checking the Kernel for the requested service.</summary>
/// <remarks>
/// The dependency resolver has the following precedence order:
/// <list type = "bullet">
/// <item>
/// <description>The dependency is checked within the
/// <see cref = "CreationContext" />
/// </description>
/// </item>
/// <item>
/// <description>The dependency is checked within the
/// <see cref = "IHandler" />
/// instance for the component</description>
/// </item>
/// <item>
/// <description>The dependency is checked within the registered
/// <see cref = "ISubDependencyResolver" />
/// s</description>
/// </item>
/// <item>
/// <description>Finally the resolver tries the normal flow which is using the configuration or other component to satisfy the dependency</description>
/// </item>
/// </list>
/// </remarks>
/// <param name = "context">Creation context, which is a resolver itself</param>
/// <param name = "contextHandlerResolver">Parent resolver</param>
/// <param name = "model">Model of the component that is requesting the dependency</param>
/// <param name = "dependency">The dependency model</param>
/// <returns>The dependency resolved value or null</returns>
public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
var value = ResolveCore(context, contextHandlerResolver, model, dependency);
if (value == null)
{
if (dependency.HasDefaultValue)
{
value = dependency.DefaultValue;
}
else if (dependency.IsOptional == false)
{
var message = String.Format(
"Could not resolve non-optional dependency for '{0}' ({1}). Parameter '{2}' type '{3}'",
model.Name,
model.Implementation != null ? model.Implementation.FullName : "-unknown-",
dependency.DependencyKey,
dependency.TargetType.FullName);
throw new DependencyResolverException(message);
}
}
dependencyResolvingDelegate(model, dependency, value);
return value;
}
protected virtual bool CanResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency)
{
if (dependency.ReferencedComponentName != null)
{
// User wants to override
return HasComponentInValidState(dependency.ReferencedComponentName, dependency, context);
}
if (dependency.Parameter != null)
{
return true;
}
if (typeof(IKernel).IsAssignableFrom(dependency.TargetItemType))
{
return true;
}
if (dependency.TargetItemType.IsPrimitiveType())
{
return false;
}
return HasAnyComponentInValidState(dependency.TargetItemType, dependency, context);
}
/// <summary>This method rebuild the context for the parameter type. Naive implementation.</summary>
protected virtual CreationContext RebuildContextForParameter(CreationContext current, Type parameterType)
{
if (parameterType.GetTypeInfo().ContainsGenericParameters)
{
return current;
}
return new CreationContext(parameterType, current, false);
}
protected virtual object ResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency)
{
if (dependency.ReferencedComponentName != null)
{
return ResolveFromKernelByName(context, model, dependency);
}
if (dependency.Parameter != null)
{
return ResolveFromParameter(context, model, dependency);
}
if (typeof(IKernel).IsAssignableFrom(dependency.TargetItemType))
{
return kernel;
}
if (dependency.TargetItemType.IsPrimitiveType())
{
// we can shortcircuit it here, since we know we won't find any components for value type service as those are not legal.
return null;
}
return ResolveFromKernelByType(context, model, dependency);
}
private bool CanResolveFromContext(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model,
DependencyModel dependency)
{
return context != null && context.CanResolve(context, contextHandlerResolver, model, dependency);
}
private bool CanResolveFromContextHandlerResolver(CreationContext context, ISubDependencyResolver contextHandlerResolver,
ComponentModel model, DependencyModel dependency)
{
return contextHandlerResolver != null && contextHandlerResolver.CanResolve(context, contextHandlerResolver, model, dependency);
}
private bool CanResolveFromHandler(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model,
DependencyModel dependency)
{
var handler = kernel.GetHandler(model.Name);
var b = handler != null && handler != contextHandlerResolver && handler.CanResolve(context, contextHandlerResolver, model, dependency);
return b;
}
private bool CanResolveFromSubResolvers(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model,
DependencyModel dependency)
{
return subResolvers.Count > 0 && subResolvers.Any(s => s.CanResolve(context, contextHandlerResolver, model, dependency));
}
private bool HasAnyComponentInValidState(Type service, DependencyModel dependency, CreationContext context)
{
IHandler firstHandler;
if (context != null && context.IsResolving)
{
firstHandler = kernel.LoadHandlerByType(dependency.DependencyKey, service, context.AdditionalArguments);
}
else
{
firstHandler = kernel.GetHandler(service);
}
if (firstHandler == null)
{
return false;
}
if (context == null || firstHandler.IsBeingResolvedInContext(context) == false)
{
if (IsHandlerInValidState(firstHandler))
{
return true;
}
}
var handlers = kernel.GetHandlers(service);
var nonResolvingHandlers = handlers.Where(handler => handler.IsBeingResolvedInContext(context) == false).ToList();
RebuildOpenGenericHandlersWithClosedGenericSubHandlers(service, context, nonResolvingHandlers);
return nonResolvingHandlers.Any(handler => IsHandlerInValidState(handler));
}
private void RebuildOpenGenericHandlersWithClosedGenericSubHandlers(Type service, CreationContext context, List<IHandler> nonResolvingHandlers)
{
if (context.RequestedType != null && service.GetTypeInfo().IsGenericType)
{
// Remove DefaultGenericHandlers
var genericHandlers = nonResolvingHandlers.OfType<DefaultGenericHandler>().ToList();
nonResolvingHandlers.RemoveAll(x => genericHandlers.Contains(x));
// Convert open generic handlers to closed generic sub handlers
var openGenericContext = RebuildContextForParameter(context, service);
var closedGenericSubHandlers = genericHandlers.Select(x => x.ConvertToClosedGenericHandler(service, openGenericContext)).ToList();
// Update nonResolvingHandlers with closed generic sub handlers with potentially valid state
nonResolvingHandlers.AddRange(closedGenericSubHandlers);
}
}
private bool HasComponentInValidState(string key, DependencyModel dependency, CreationContext context)
{
IHandler handler;
if (context != null && context.IsResolving)
{
handler = kernel.LoadHandlerByName(key, dependency.TargetItemType, context.AdditionalArguments);
}
else
{
handler = kernel.GetHandler(key);
}
return IsHandlerInValidState(handler) && handler.IsBeingResolvedInContext(context) == false;
}
private object ResolveCore(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
{
// 1 - check for the dependency on CreationContext, if present
if (CanResolveFromContext(context, contextHandlerResolver, model, dependency))
{
return context.Resolve(context, contextHandlerResolver, model, dependency);
}
// 2 - check with the model's handler, if not the same as the parent resolver
var handler = kernel.GetHandler(model.Name);
if (handler != contextHandlerResolver && handler.CanResolve(context, contextHandlerResolver, model, dependency))
{
return handler.Resolve(context, contextHandlerResolver, model, dependency);
}
// 3 - check within parent resolver, if present
if (CanResolveFromContextHandlerResolver(context, contextHandlerResolver, model, dependency))
{
return contextHandlerResolver.Resolve(context, contextHandlerResolver, model, dependency);
}
// 4 - check within subresolvers
if (subResolvers.Count > 0)
{
for (var index = 0; index < subResolvers.Count; index++)
{
var subResolver = subResolvers[index];
if (subResolver.CanResolve(context, contextHandlerResolver, model, dependency))
{
return subResolver.Resolve(context, contextHandlerResolver, model, dependency);
}
}
}
// 5 - normal flow, checking against the kernel
return ResolveFromKernel(context, model, dependency);
}
private object ResolveFromKernelByName(CreationContext context, ComponentModel model, DependencyModel dependency)
{
var handler = kernel.LoadHandlerByName(dependency.ReferencedComponentName, dependency.TargetItemType, context.AdditionalArguments);
// never (famous last words) this should really happen as we're the good guys and we call CanResolve before trying to resolve but let's be safe.
if (handler == null)
{
throw new DependencyResolverException(
string.Format(
"Missing dependency.{2}Component {0} has a dependency on component {1}, which was not registered.{2}Make sure the dependency is correctly registered in the container as a service.",
model.Name,
dependency.ReferencedComponentName,
Environment.NewLine));
}
var contextRebuilt = RebuildContextForParameter(context, dependency.TargetItemType);
return handler.Resolve(contextRebuilt);
}
private object ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency)
{
IHandler handler;
try
{
handler = TryGetHandlerFromKernel(dependency, context);
}
catch (HandlerException exception)
{
if (dependency.HasDefaultValue)
{
return dependency.DefaultValue;
}
throw new DependencyResolverException(
string.Format(
"Missing dependency.{2}Component {0} has a dependency on {1}, which could not be resolved.{2}Make sure the dependency is correctly registered in the container as a service, or provided as inline argument.",
model.Name,
dependency.TargetItemType,
Environment.NewLine),
exception);
}
if (handler == null)
{
if (dependency.HasDefaultValue)
{
return dependency.DefaultValue;
}
throw new DependencyResolverException(
string.Format(
"Cycle detected in configuration.{2}Component {0} has a dependency on {1}, but it doesn't provide an override.{2}You must provide an override if a component has a dependency on a service that it - itself - provides.",
model.Name,
dependency.TargetItemType,
Environment.NewLine));
}
context = RebuildContextForParameter(context, dependency.TargetItemType);
return handler.Resolve(context);
}
private object ResolveFromParameter(CreationContext context, ComponentModel model, DependencyModel dependency)
{
converter.Context.Push(model, context);
try
{
if (dependency.Parameter.Value != null || dependency.Parameter.ConfigValue == null)
{
return converter.PerformConversion(dependency.Parameter.Value, dependency.TargetItemType);
}
else
{
return converter.PerformConversion(dependency.Parameter.ConfigValue, dependency.TargetItemType);
}
}
catch (ConverterException e)
{
throw new DependencyResolverException(
string.Format("Could not convert parameter '{0}' to type '{1}'.", dependency.Parameter.Name, dependency.TargetItemType.Name), e);
}
finally
{
converter.Context.Pop();
}
}
private IHandler TryGetHandlerFromKernel(DependencyModel dependency, CreationContext context)
{
// we are doing it in two stages because it is likely to be faster to a lookup
// by key than a linear search
var handler = kernel.LoadHandlerByType(dependency.DependencyKey, dependency.TargetItemType, context.AdditionalArguments);
if (handler == null)
{
throw new HandlerException(string.Format("Handler for {0} was not found.", dependency.TargetItemType), null);
}
if (handler.IsBeingResolvedInContext(context) == false)
{
return handler;
}
// make a best effort to find another one that fit
var handlers = kernel.GetHandlers(dependency.TargetItemType);
foreach (var maybeCorrectHandler in handlers)
{
if (maybeCorrectHandler.IsBeingResolvedInContext(context) == false)
{
handler = maybeCorrectHandler;
break;
}
}
return handler;
}
private static bool IsHandlerInValidState(IHandler handler)
{
if (handler == null)
{
return false;
}
return handler.CurrentState == HandlerState.Valid;
}
}
}