-
Notifications
You must be signed in to change notification settings - Fork 459
/
Copy pathBasedOnDescriptor.cs
514 lines (466 loc) · 14.7 KB
/
BasedOnDescriptor.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// Copyright 2004-2012 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.Registration
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Castle.Core;
using Castle.MicroKernel.Lifestyle.Scoped;
/// <summary>
/// Describes how to register a group of related types.
/// </summary>
public class BasedOnDescriptor : IRegistration
{
private readonly List<Type> potentialBases;
private Action<ComponentRegistration> configuration;
private readonly FromDescriptor from;
private readonly ServiceDescriptor service;
private Predicate<Type> ifFilter;
private Predicate<Type> unlessFilter;
/// <summary>
/// Initializes a new instance of the BasedOnDescriptor.
/// </summary>
internal BasedOnDescriptor(IEnumerable<Type> basedOn, FromDescriptor from, Predicate<Type> additionalFilters)
{
potentialBases = basedOn.ToList();
this.from = from;
service = new ServiceDescriptor(this);
If(additionalFilters);
}
/// <summary>
/// Gets the service descriptor.
/// </summary>
public ServiceDescriptor WithService
{
get { return service; }
}
/// <summary>
/// Allows a type to be registered multiple times.
/// </summary>
public FromDescriptor AllowMultipleMatches()
{
return from.AllowMultipleMatches();
}
/// <summary>
/// Adds another type to be accepted as base.
/// </summary>
/// <param name = "basedOn"> The base type. </param>
/// <returns> The descriptor for the type. </returns>
public BasedOnDescriptor OrBasedOn(Type basedOn)
{
potentialBases.Add(basedOn);
return this;
}
/// <summary>
/// Allows customized configurations of each matching type.
/// </summary>
/// <param name = "configurer"> The configuration action. </param>
/// <returns> </returns>
public BasedOnDescriptor Configure(Action<ComponentRegistration> configurer)
{
configuration += configurer;
return this;
}
/// <summary>
/// Allows customized configurations of each matching component with implementation type that is
/// assignable to
/// <typeparamref name = "TComponentImplementationType" />
/// .
/// </summary>
/// <typeparam name = "TComponentImplementationType"> The type assignable from. </typeparam>
/// <param name = "configurer"> The configuration action. </param>
/// <returns> </returns>
public BasedOnDescriptor ConfigureFor<TComponentImplementationType>(Action<ComponentRegistration> configurer)
{
return ConfigureIf(r => typeof(TComponentImplementationType).IsAssignableFrom(r.Implementation), configurer);
}
/// <summary>
/// Allows customized configurations of each matching component that satisfies supplied <paramref name = "condition" />.
/// </summary>
/// <param name = "condition"> Condition to satisfy </param>
/// <param name = "configurer"> The configuration action, executed only for components for which <paramref name = "condition" /> evaluates to <c>true</c> . </param>
/// <returns> </returns>
public BasedOnDescriptor ConfigureIf(Predicate<ComponentRegistration> condition,
Action<ComponentRegistration> configurer)
{
configuration += r =>
{
if (condition(r))
{
configurer(r);
}
};
return this;
}
/// <summary>
/// Allows customized configurations of each matching component that satisfies supplied <paramref name = "condition" /> and alternative configuration for the rest of components.
/// </summary>
/// <param name = "condition"> Condition to satisfy </param>
/// <param name = "configurerWhenTrue"> The configuration action, executed only for components for which <paramref name = "condition" /> evaluates to <c>true</c> . </param>
/// <param name = "configurerWhenFalse"> The configuration action, executed only for components for which <paramref name = "condition" /> evaluates to <c>false</c> . </param>
/// <returns> </returns>
public BasedOnDescriptor ConfigureIf(Predicate<ComponentRegistration> condition,
Action<ComponentRegistration> configurerWhenTrue,
Action<ComponentRegistration> configurerWhenFalse)
{
configuration += r =>
{
if (condition(r))
{
configurerWhenTrue(r);
}
else
{
configurerWhenFalse(r);
}
};
return this;
}
/// <summary>
/// Assigns a conditional predication which must be satisfied.
/// </summary>
/// <param name = "ifFilter"> The predicate to satisfy. </param>
/// <returns> </returns>
public BasedOnDescriptor If(Predicate<Type> ifFilter)
{
this.ifFilter += ifFilter;
return this;
}
/// <summary>
/// Assigns a conditional predication which must not be satisfied.
/// </summary>
/// <param name = "unlessFilter"> The predicate not to satisify. </param>
/// <returns> </returns>
public BasedOnDescriptor Unless(Predicate<Type> unlessFilter)
{
this.unlessFilter += unlessFilter;
return this;
}
/// <summary>
/// Uses all interfaces implemented by the type (or its base types) as well as their base interfaces.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor WithServiceAllInterfaces()
{
return WithService.AllInterfaces();
}
/// <summary>
/// Uses the base type matched on.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor WithServiceBase()
{
return WithService.Base();
}
/// <summary>
/// Uses all interfaces that have names matched by implementation type name.
/// Matches Foo to IFoo, SuperFooExtended to IFoo and IFooExtended etc
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor WithServiceDefaultInterfaces()
{
return WithService.DefaultInterfaces();
}
/// <summary>
/// Uses the first interface of a type. This method has non-deterministic behavior when type implements more than one interface!
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor WithServiceFirstInterface()
{
return WithService.FirstInterface();
}
/// <summary>
/// Uses <paramref name = "implements" /> to lookup the sub interface.
/// For example: if you have IService and
/// IProductService : ISomeInterface, IService, ISomeOtherInterface.
/// When you call FromInterface(typeof(IService)) then IProductService
/// will be used. Useful when you want to register _all_ your services
/// and but not want to specify all of them.
/// </summary>
/// <param name = "implements"> </param>
/// <returns> </returns>
public BasedOnDescriptor WithServiceFromInterface(Type implements)
{
return WithService.FromInterface(implements);
}
/// <summary>
/// Uses base type to lookup the sub interface.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor WithServiceFromInterface()
{
return WithService.FromInterface();
}
/// <summary>
/// Assigns a custom service selection strategy.
/// </summary>
/// <param name = "selector"> </param>
/// <returns> </returns>
public BasedOnDescriptor WithServiceSelect(ServiceDescriptor.ServiceSelector selector)
{
return WithService.Select(selector);
}
/// <summary>
/// Uses the type itself.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor WithServiceSelf()
{
return WithService.Self();
}
/// <summary>
/// Sets component lifestyle to specified one.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleCustom(Type customLifestyleType)
{
return Configure(c => c.LifestyleCustom(customLifestyleType));
}
/// <summary>
/// Sets component lifestyle to specified one.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleCustom<TLifestyleManager>() where TLifestyleManager : ILifestyleManager, new()
{
return Configure(c => c.LifestyleCustom<TLifestyleManager>());
}
/// <summary>
/// Sets component lifestyle to per thread.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestylePerThread()
{
return Configure(c => c.LifestylePerThread());
}
/// <summary>
/// Sets component lifestyle to scoped per explicit scope.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleScoped()
{
return Configure(c => c.LifestyleScoped());
}
/// <summary>
/// Sets component lifestyle to scoped per explicit scope.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleScoped(Type scopeAccessorType)
{
return Configure(c => c.LifestyleScoped(scopeAccessorType));
}
/// <summary>
/// Sets component lifestyle to scoped per explicit scope.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleScoped<TScopeAccessor>() where TScopeAccessor : IScopeAccessor, new()
{
return Configure(c => c.LifestyleScoped<TScopeAccessor>());
}
/// <summary>
/// Sets component lifestyle to scoped per component <typeparamref name = "TBaseForRoot" />.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleBoundTo<TBaseForRoot>() where TBaseForRoot : class
{
return Configure(c => c.LifestyleBoundTo<TBaseForRoot>());
}
/// <summary>
/// Sets component lifestyle to scoped per nearest component on the resolution stack where implementation type is assignable to <typeparamref name = "TBaseForRoot" /> .
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleBoundToNearest<TBaseForRoot>() where TBaseForRoot : class
{
return Configure(c => c.LifestyleBoundToNearest<TBaseForRoot>());
}
/// <summary>
/// Sets component lifestyle to pooled. If <paramref name = "initialSize" /> or <paramref name = "maxSize" /> are not set default values will be used.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestylePooled(int? initialSize = null, int? maxSize = null)
{
return Configure(c => c.LifestylePooled(initialSize, maxSize));
}
/// <summary>
/// Sets component lifestyle to singleton.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleSingleton()
{
return Configure(c => c.LifestyleSingleton());
}
/// <summary>
/// Sets component lifestyle to transient.
/// </summary>
/// <returns> </returns>
public BasedOnDescriptor LifestyleTransient()
{
return Configure(c => c.LifestyleTransient());
}
/// <summary>
/// Assigns the supplied service types.
/// </summary>
/// <param name = "types"> </param>
/// <returns> </returns>
public BasedOnDescriptor WithServices(IEnumerable<Type> types)
{
return WithService.Select(types);
}
/// <summary>
/// Assigns the supplied service types.
/// </summary>
/// <param name = "types"> </param>
/// <returns> </returns>
public BasedOnDescriptor WithServices(params Type[] types)
{
return WithService.Select(types);
}
protected virtual bool Accepts(Type type, out Type[] baseTypes)
{
return IsBasedOn(type, out baseTypes)
&& ExecuteIfCondition(type)
&& ExecuteUnlessCondition(type) == false;
}
protected bool ExecuteIfCondition(Type type)
{
if (ifFilter == null)
{
return true;
}
foreach (Predicate<Type> filter in ifFilter.GetInvocationList())
{
if (filter(type) == false)
{
return false;
}
}
return true;
}
protected bool ExecuteUnlessCondition(Type type)
{
if (unlessFilter == null)
{
return false;
}
foreach (Predicate<Type> filter in unlessFilter.GetInvocationList())
{
if (filter(type))
{
return true;
}
}
return false;
}
protected bool IsBasedOn(Type type, out Type[] baseTypes)
{
var actuallyBasedOn = new List<Type>();
foreach (var potentialBase in potentialBases)
{
if (potentialBase.GetTypeInfo().IsAssignableFrom(type))
{
actuallyBasedOn.Add(potentialBase);
}
else if (potentialBase.GetTypeInfo().IsGenericTypeDefinition)
{
if (potentialBase.GetTypeInfo().IsInterface)
{
if (IsBasedOnGenericInterface(type, potentialBase, out baseTypes))
{
actuallyBasedOn.AddRange(baseTypes);
}
}
if (IsBasedOnGenericClass(type, potentialBase, out baseTypes))
{
actuallyBasedOn.AddRange(baseTypes);
}
}
}
baseTypes = actuallyBasedOn.Distinct().ToArray();
return baseTypes.Length > 0;
}
internal bool TryRegister(Type type, IKernel kernel)
{
Type[] baseTypes;
if (!Accepts(type, out baseTypes))
{
return false;
}
var defaults = CastleComponentAttribute.GetDefaultsFor(type);
var serviceTypes = service.GetServices(type, baseTypes);
if (serviceTypes.Count == 0 && defaults.Services.Length > 0)
{
serviceTypes = defaults.Services;
}
var registration = Component.For(serviceTypes);
registration.ImplementedBy(type);
if (configuration != null)
{
configuration(registration);
}
if (String.IsNullOrEmpty(registration.Name) && !String.IsNullOrEmpty(defaults.Name))
{
registration.Named(defaults.Name);
}
else
{
registration.RegisterOptionally();
}
kernel.Register(registration);
return true;
}
private static bool IsBasedOnGenericClass(Type type, Type basedOn, out Type[] baseTypes)
{
while (type != null)
{
if (type.GetTypeInfo().IsGenericType &&
type.GetGenericTypeDefinition() == basedOn)
{
baseTypes = new[] { type };
return true;
}
type = type.GetTypeInfo().BaseType;
}
baseTypes = null;
return false;
}
private static bool IsBasedOnGenericInterface(Type type, Type basedOn, out Type[] baseTypes)
{
var types = new List<Type>(4);
foreach (var @interface in type.GetInterfaces())
{
if (@interface.GetTypeInfo().IsGenericType &&
@interface.GetGenericTypeDefinition() == basedOn)
{
if (@interface.DeclaringType == null &&
@interface.GetTypeInfo().ContainsGenericParameters)
{
types.Add(@interface.GetGenericTypeDefinition());
}
else
{
types.Add(@interface);
}
}
}
baseTypes = types.ToArray();
return baseTypes.Length > 0;
}
void IRegistration.Register(IKernelInternal kernel)
{
((IRegistration)from).Register(kernel);
}
}
}