/
Container.cs
11171 lines (9565 loc) · 604 KB
/
Container.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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
The MIT License (MIT)
Copyright (c) 2013-2016 Maksim Volkau
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.
*/
namespace DryIoc
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using ImTools;
/// <summary>IoC Container. Documentation is available at https://bitbucket.org/dadhi/dryioc. </summary>
public sealed partial class Container : IContainer, IScopeAccess
{
/// <summary>Creates new container with default rules <see cref="DryIoc.Rules.Default"/>.</summary>
public Container() : this(Rules.Default, Ref.Of(Registry.Default), new SingletonScope())
{ }
/// <summary>Creates new container, optionally providing <see cref="Rules"/> to modify default container behavior.</summary>
/// <param name="rules">(optional) Rules to modify container default resolution behavior.
/// If not specified, then <see cref="DryIoc.Rules.Default"/> will be used.</param>
/// <param name="scopeContext">(optional) Scope context to use for <see cref="Reuse.InCurrentScope"/>, default is <see cref="ThreadScopeContext"/>.</param>
public Container(Rules rules = null, IScopeContext scopeContext = null)
: this(rules ?? Rules.Default, Ref.Of(Registry.Default), new SingletonScope(), scopeContext)
{ }
/// <summary>Creates new container with configured rules.</summary>
/// <param name="configure">Delegate gets <see cref="DryIoc.Rules.Default"/> as input and may return configured rules.</param>
/// <param name="scopeContext">(optional) Scope context to use for <see cref="Reuse.InCurrentScope"/>, default is <see cref="ThreadScopeContext"/>.</param>
public Container(Func<Rules, Rules> configure, IScopeContext scopeContext = null)
: this(configure.ThrowIfNull()(Rules.Default) ?? Rules.Default, scopeContext)
{ }
/// <summary>Outputs scope info for open scope.</summary> <returns>Info about scoped container</returns>
public override string ToString()
{
var scope = ((IScopeAccess)this).GetCurrentScope();
var scopeStr
= scope == null ? "Container"
: _scopeContext != null ? "Ambiently scoped container: " + scope
: "Scoped container: " + scope;
if (IsDisposed)
scopeStr = "Disposed (!) " + scopeStr;
return scopeStr;
}
/// <summary>Shares all of container state except Cache and specifies new rules.</summary>
/// <param name="configure">(optional) Configure rules, if not specified then uses Rules from current container.</param>
/// <param name="scopeContext">(optional) New scope context, if not specified then uses context from current container.</param>
/// <returns>New container.</returns>
public IContainer With(Func<Rules, Rules> configure = null, IScopeContext scopeContext = null)
{
ThrowIfContainerDisposed();
var rules = configure == null ? Rules : configure(Rules);
scopeContext = scopeContext ?? _scopeContext;
var registryWithoutCache = Ref.Of(_registry.Value.WithoutCache());
return new Container(rules, registryWithoutCache, _singletonScope, scopeContext, _openedScope, _disposed, RootContainer);
}
/// <summary>Produces new container which prevents any further registrations.</summary>
/// <param name="ignoreInsteadOfThrow">(optional) Controls what to do with the next registration: ignore or throw exception.
/// Throws exception by default.</param>
/// <returns>New container preserving all current container state but disallowing registrations.</returns>
public IContainer WithNoMoreRegistrationAllowed(bool ignoreInsteadOfThrow = false)
{
var readonlyRegistry = Ref.Of(_registry.Value.WithNoMoreRegistrationAllowed(ignoreInsteadOfThrow));
return new Container(Rules, readonlyRegistry, _singletonScope, _scopeContext, _openedScope, _disposed, RootContainer);
}
/// <summary>Returns new container with all expression, delegate, items cache removed/reset.
/// It will preserve resolved services in Singleton/Current scope.</summary>
/// <returns>New container with empty cache.</returns>
public IContainer WithoutCache()
{
ThrowIfContainerDisposed();
var registryWithoutCache = Ref.Of(_registry.Value.WithoutCache());
return new Container(Rules, registryWithoutCache, _singletonScope, _scopeContext, _openedScope, _disposed, RootContainer);
}
/// <summary>Creates new container with state shared with original except singletons and cache.
/// Dropping cache is required because singletons are cached in resolution state.</summary>
/// <returns>New container with empty Singleton Scope.</returns>
public IContainer WithoutSingletonsAndCache()
{
ThrowIfContainerDisposed();
var registryWithoutCache = Ref.Of(_registry.Value.WithoutCache());
var newSingletons = new SingletonScope();
return new Container(Rules, registryWithoutCache, newSingletons, _scopeContext, _openedScope, _disposed, RootContainer);
}
/// <summary>Shares all parts with original container But copies registration, so the new registration
/// won't be visible in original. Registrations include decorators and wrappers as well.</summary>
/// <param name="preserveCache">(optional) If set preserves cache if you know what to do.</param>
/// <returns>New container with copy of all registrations.</returns>
public IContainer WithRegistrationsCopy(bool preserveCache = false)
{
ThrowIfContainerDisposed();
var newRegistry = preserveCache ? _registry.NewRef() : Ref.Of(_registry.Value.WithoutCache());
return new Container(Rules, newRegistry, _singletonScope, _scopeContext, _openedScope, _disposed, RootContainer);
}
/// <summary>Returns ambient scope context associated with container.</summary>
public IScopeContext ScopeContext { get { return _scopeContext; } }
/// <summary>Creates new container with new opened scope, with shared registrations, singletons and resolutions cache.
/// If container uses ambient scope context, then this method sets new opened scope as current scope in the context.
/// In case of previous open scope, new open scope references old one as a parent.
/// </summary>
/// <param name="name">(optional) Name for opened scope to allow reuse to identify the scope.</param>
/// <param name="configure">(optional) Configure rules, if not specified then uses Rules from current container.</param>
/// <returns>New container with different current scope.</returns>
/// <example><code lang="cs"><![CDATA[
/// using (var scoped = container.OpenScope())
/// {
/// var handler = scoped.Resolve<IHandler>();
/// handler.Handle(data);
/// }
/// ]]></code></example>
public IContainer OpenScope(object name = null, Func<Rules, Rules> configure = null)
{
ThrowIfContainerDisposed();
if (name == null)
name = _openedScope != null ? null
: _scopeContext != null ? _scopeContext.RootScopeName
: NonAmbientRootScopeName;
var nestedOpenedScope = new Scope(_openedScope, name);
// Replacing current context scope with new nested only if current is the same as nested parent, otherwise throw.
if (_scopeContext != null)
_scopeContext.SetCurrent(scope =>
nestedOpenedScope.ThrowIf(scope != _openedScope, Error.NotDirectScopeParent, _openedScope, scope));
var rules = configure == null ? Rules : configure(Rules);
return new Container(rules, _registry, _singletonScope, _scopeContext, nestedOpenedScope, _disposed, RootContainer ?? this);
}
/// <summary>The default name of root scope without ambient context.</summary>
public static readonly object NonAmbientRootScopeName = "NonAmbientRootScope";
/// <summary>Creates container (facade) that fallbacks to this container for unresolved services.
/// Facade is the new empty container, with the same rules and scope context as current container.
/// It could be used for instance to create Test facade over original container with replacing some services with test ones.</summary>
/// <remarks>Singletons from container are not reused by facade - when you resolve singleton directly from parent and then ask for it from child, it will return another object.
/// To achieve that you may use <see cref="IContainer.OpenScope"/> with <see cref="Reuse.InCurrentScope"/>.</remarks>
/// <returns>New facade container.</returns>
public IContainer CreateFacade()
{
ThrowIfContainerDisposed();
return new Container(Rules.WithFallbackContainer(this), _scopeContext);
}
/// <summary>Clears cache for specified service(s).
/// But does not clear instances of already resolved/created singletons and scoped services!</summary>
/// <param name="serviceType">Target service type.</param>
/// <param name="factoryType">(optional) If not specified, clears cache for all <see cref="FactoryType"/>.</param>
/// <param name="serviceKey">(optional) If omitted, the cache will be cleared for all resgitrations of <paramref name="serviceType"/>.</param>
/// <returns>True if target service was found, false - otherwise.</returns>
public bool ClearCache(Type serviceType, FactoryType? factoryType = null, object serviceKey = null)
{
if (factoryType != null)
return _registry.Value.ClearCache(serviceType, serviceKey, factoryType.Value);
var registry = _registry.Value;
var clearedServices = registry.ClearCache(serviceType, serviceKey, FactoryType.Service);
var clearWrapper = registry.ClearCache(serviceType, serviceKey, FactoryType.Wrapper);
var clearDecorator = registry.ClearCache(serviceType, serviceKey, FactoryType.Decorator);
return clearedServices || clearWrapper || clearDecorator;
}
/// <summary>Dispose either open scope, or container with singletons, if no scope opened.</summary>
public void Dispose()
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) != 0)
return;
// for container created with OpenScope
if (_openedScope != null &&
!(Rules.ImplicitOpenedRootScope && _openedScope.Parent == null && _scopeContext == null))
{
if (_openedScope != null)
{
_openedScope.Dispose();
if (_scopeContext != null)
_scopeContext.SetCurrent(scope => scope == _openedScope ? scope.Parent : scope);
}
}
else // whole Container with singletons.
{
if (_openedScope != null)
_openedScope.Dispose();
if (_scopeContext != null)
_scopeContext.Dispose();
_singletonScope.Dispose();
_registry.Swap(Registry.Empty);
_defaultFactoryDelegateCache = Ref.Of(ImMap<Type, FactoryDelegate>.Empty);
Rules = Rules.Default;
}
}
/// <summary>Scope containing container singletons.</summary>
public IScope SingletonScope { get { return _singletonScope; } }
/// <summary>Returns root for scoped container or null for root itself.</summary>
public readonly Container RootContainer;
#region Static state
// todo: v3: remove
/// <summary>State parameter expression in FactoryDelegate.</summary>
public static readonly ParameterExpression StateParamExpr =
Expression.Parameter(typeof(object[]), "state");
/// <summary>Resolver context parameter expression in FactoryDelegate.</summary>
public static readonly ParameterExpression ResolverContextParamExpr =
Expression.Parameter(typeof(IResolverContext), "r");
/// <summary>Resolver parameter expression in FactoryDelegate.</summary>
public static readonly Expression ResolverExpr =
Expression.Property(ResolverContextParamExpr, "Resolver");
/// <summary>Resolver parameter expression in FactoryDelegate.</summary>
public static readonly Expression RootResolverExpr =
Expression.Call(typeof(ResolverContext), "RootResolver", ArrayTools.Empty<Type>(), ResolverContextParamExpr);
/// <summary>Returns <see cref="ResolverExpr"/> or <see cref="RootResolverExpr"/> based on request.</summary>
public static Expression GetResolverExpr(Request request)
{
return request.IsSingletonOrDependencyOfSingleton ? RootResolverExpr : ResolverExpr;
}
/// <summary>Resolver parameter expression in FactoryDelegate.</summary>
public static readonly Expression SingletonScopeExpr =
Expression.Call(typeof(ResolverContext), "SingletonScope", ArrayTools.Empty<Type>(), ResolverContextParamExpr);
/// <summary>Access to scopes in FactoryDelegate.</summary>
public static readonly Expression ScopesExpr =
Expression.Property(ResolverContextParamExpr, "Scopes");
/// <summary>Resolver parameter expression in FactoryDelegate.</summary>
public static readonly Expression RootScopesExpr =
Expression.Call(typeof(ResolverContext), "RootScopes", ArrayTools.Empty<Type>(), ResolverContextParamExpr);
/// <summary>Returns <see cref="ScopesExpr"/> or <see cref="RootResolverExpr"/> based on request.</summary>
public static Expression GetScopesExpr(Request request)
{
return request.IsSingletonOrDependencyOfSingleton ? RootScopesExpr : ScopesExpr;
}
/// <summary>Resolution scope parameter expression in FactoryDelegate.</summary>
public static readonly ParameterExpression ResolutionScopeParamExpr =
Expression.Parameter(typeof(IScope), "scope");
internal static Expression GetResolutionScopeExpression(Request request)
{
if (request.Scope != null)
return ResolutionScopeParamExpr;
// the only situation when we could be here: the root resolution call
// and scope was not created on the boundary of Resolve call.
var parent = request.Enumerate().Last();
var container = request.Container;
var registeredServiceType = container.GetWrappedType(parent.ServiceType, parent.RequiredServiceType);
var parentServiceTypeExpr = Expression.Constant(registeredServiceType, typeof(Type));
var parentServiceKeyExpr = container.GetOrAddStateItemExpression(parent.ServiceKey, typeof(object));
// if assign in expression is supported then use it.
var scopesExpr = GetScopesExpr(request);
if (_expressionAssignMethod != null)
{
var getOrNewScopeExpr = Expression.Call(scopesExpr, "GetOrNewResolutionScope",
ArrayTools.Empty<Type>(), ResolutionScopeParamExpr, parentServiceTypeExpr, parentServiceKeyExpr);
var parameters = new object[] { ResolutionScopeParamExpr, getOrNewScopeExpr };
return (Expression)_expressionAssignMethod.Value.Invoke(null, parameters);
}
return Expression.Call(scopesExpr, "GetOrCreateResolutionScope",
ArrayTools.Empty<Type>(), ResolutionScopeParamExpr, parentServiceTypeExpr, parentServiceKeyExpr);
}
private static readonly Lazy<MethodInfo> _expressionAssignMethod = new Lazy<MethodInfo>(() =>
typeof(Expression).GetMethodOrNull("Assign", typeof(Expression), typeof(Expression)));
#endregion
#region IRegistrator
/// <summary>Returns all registered service factories with their Type and optional Key.</summary>
/// <returns>Existing registrations.</returns>
/// <remarks>Decorator and Wrapper types are not included.</remarks>
public IEnumerable<ServiceRegistrationInfo> GetServiceRegistrations()
{
return _registry.Value.GetServiceRegistrations();
}
/// <summary>Stores factory into container using <paramref name="serviceType"/> and <paramref name="serviceKey"/> as key
/// for later lookup.</summary>
/// <param name="factory">Any subtypes of <see cref="Factory"/>.</param>
/// <param name="serviceType">Type of service to resolve later.</param>
/// <param name="serviceKey">(optional) Service key of any type with <see cref="object.GetHashCode"/> and <see cref="object.Equals(object)"/>
/// implemented.</param>
/// <param name="ifAlreadyRegistered">(optional) Says how to handle existing registration with the same
/// <paramref name="serviceType"/> and <paramref name="serviceKey"/>.</param>
/// <param name="isStaticallyChecked">Confirms that service and implementation types are statically checked by compiler.</param>
/// <returns>True if factory was added to registry, false otherwise.
/// False may be in case of <see cref="IfAlreadyRegistered.Keep"/> setting and already existing factory.</returns>
public void Register(Factory factory, Type serviceType, object serviceKey, IfAlreadyRegistered ifAlreadyRegistered, bool isStaticallyChecked)
{
ThrowIfContainerDisposed();
ThrowIfInvalidRegistration(factory, serviceType, serviceKey, isStaticallyChecked);
if (ifAlreadyRegistered == IfAlreadyRegistered.AppendNotKeyed)
ifAlreadyRegistered = Rules.DefaultIfAlreadyRegistered;
// Improves performance a bit by attempt to swapping registry while it is still unchanged,
// if attempt fails then fallback to normal Swap with retry.
var registry = _registry.Value;
if (!_registry.TrySwapIfStillCurrent(registry, registry.Register(factory, serviceType, ifAlreadyRegistered, serviceKey)))
_registry.Swap(r => r.Register(factory, serviceType, ifAlreadyRegistered, serviceKey));
_defaultFactoryDelegateCache = _registry.Value.DefaultFactoryDelegateCache;
}
private void ThrowIfInvalidRegistration(Factory factory, Type serviceType, object serviceKey, bool isStaticallyChecked)
{
if (!isStaticallyChecked)
{
serviceType.ThrowIfNull();
factory.ThrowIfNull();
}
var setup = factory.Setup;
if (setup.FactoryType != FactoryType.Wrapper)
{
if ((factory.Reuse ?? Rules.DefaultReuseInsteadOfTransient) == Reuse.Transient &&
!factory.Setup.UseParentReuse &&
!(factory.FactoryType == FactoryType.Decorator && ((Setup.DecoratorSetup)factory.Setup).UseDecorateeReuse) &&
(factory.ImplementationType ?? serviceType).IsAssignableTo(typeof(IDisposable)) &&
!setup.AllowDisposableTransient && Rules.ThrowOnRegisteringDisposableTransient)
{
Throw.It(Error.RegisteredDisposableTransientWontBeDisposedByContainer,
serviceType, serviceKey ?? "{no key}", factory);
}
}
else if (serviceType.IsGeneric() &&
!((Setup.WrapperSetup)setup).AlwaysWrapsRequiredServiceType &&
((Setup.WrapperSetup)setup).Unwrap == null)
{
var typeArgCount = serviceType.GetGenericParamsAndArgs().Length;
var typeArgIndex = ((Setup.WrapperSetup)setup).WrappedServiceTypeArgIndex;
Throw.If(typeArgCount > 1 && typeArgIndex == -1,
Error.GenericWrapperWithMultipleTypeArgsShouldSpecifyArgIndex, serviceType);
var index = typeArgIndex != -1 ? typeArgIndex : 0;
Throw.If(index > typeArgCount - 1,
Error.GenericWrapperTypeArgIndexOutOfBounds, serviceType, index);
}
var reflectionFactory = factory as ReflectionFactory;
if (reflectionFactory != null)
{
if (reflectionFactory.Made.FactoryMethod == null && Rules.FactoryMethod == null)
{
var ctors = reflectionFactory.ImplementationType.GetPublicInstanceConstructors().ToArrayOrSelf();
if (ctors.Length != 1)
Throw.It(Error.NoDefinedMethodToSelectFromMultipleConstructors, reflectionFactory.ImplementationType, ctors);
else
reflectionFactory.SetKnownSingleCtor(ctors[0]);
}
if (!isStaticallyChecked &&
reflectionFactory.ImplementationType != null)
{
var implType = reflectionFactory.ImplementationType;
if (!implType.IsGenericDefinition())
{
if (implType.IsOpenGeneric())
Throw.It(Error.RegisteringNotAGenericTypedefImplType,
implType, implType.GetGenericDefinitionOrNull());
if (implType != serviceType && serviceType != typeof(object) &&
implType.GetImplementedTypes().IndexOf(t => t == serviceType) == -1)
Throw.It(Error.RegisterImplementationNotAssignableToServiceType, implType, serviceType);
}
else if (implType != serviceType)
{
// Validate that service type able to supply all type parameters to open-generic implementation type.
if (serviceType.IsGenericDefinition())
{
var implTypeParams = implType.GetGenericParamsAndArgs();
var implementedTypes = implType.GetImplementedTypes();
var implementedTypeFound = false;
var containsAllTypeParams = false;
for (var i = 0; !containsAllTypeParams && i < implementedTypes.Length; ++i)
{
var implementedType = implementedTypes[i];
implementedTypeFound = implementedType.GetGenericDefinitionOrNull() == serviceType;
containsAllTypeParams = implementedTypeFound &&
implementedType.ContainsAllGenericTypeParameters(implTypeParams);
}
if (!implementedTypeFound)
Throw.It(Error.RegisterImplementationNotAssignableToServiceType, implType, serviceType);
if (!containsAllTypeParams)
Throw.It(Error.RegisteringOpenGenericServiceWithMissingTypeArgs,
implType, serviceType,
implementedTypes.Where(t => t.GetGenericDefinitionOrNull() == serviceType));
}
else if (implType.IsGeneric() && serviceType.IsOpenGeneric())
{
Throw.It(Error.RegisteringNotAGenericTypedefServiceType,
serviceType, serviceType.GetGenericDefinitionOrNull());
}
else
Throw.It(Error.RegisteringOpenGenericImplWithNonGenericService, implType, serviceType);
}
}
}
}
/// <summary>Returns true if there is registered factory with the service type and key.
/// To check if only default factory is registered specify <see cref="DefaultKey.Value"/> as <paramref name="serviceKey"/>.
/// Otherwise, if no <paramref name="serviceKey"/> specified then True will returned for any registered factories, even keyed.
/// Additionally you can specify <paramref name="condition"/> to be applied to registered factories.</summary>
/// <param name="serviceType">Service type to look for.</param>
/// <param name="serviceKey">Service key to look for.</param>
/// <param name="factoryType">Expected registered factory type.</param>
/// <param name="condition">Expected factory condition.</param>
/// <returns>True if factory is registered, false if not.</returns>
public bool IsRegistered(Type serviceType, object serviceKey, FactoryType factoryType, Func<Factory, bool> condition)
{
ThrowIfContainerDisposed();
var factories = _registry.Value.GetRegisteredFactories(serviceType.ThrowIfNull(), serviceKey, factoryType, condition);
return !factories.IsNullOrEmpty();
}
/// <summary>Removes specified factory from registry.
/// Factory is removed only from registry, if there is relevant cache, it will be kept.
/// Use <see cref="WithoutCache"/> to remove all the cache.</summary>
/// <param name="serviceType">Service type to look for.</param>
/// <param name="serviceKey">Service key to look for.</param>
/// <param name="factoryType">Expected factory type.</param>
/// <param name="condition">Expected factory condition.</param>
public void Unregister(Type serviceType, object serviceKey, FactoryType factoryType, Func<Factory, bool> condition)
{
ThrowIfContainerDisposed();
_registry.Swap(r => r.Unregister(factoryType, serviceType, serviceKey, condition));
_defaultFactoryDelegateCache = _registry.Value.DefaultFactoryDelegateCache;
}
#endregion
#region Direct Container Resolve methods to avoid interface dispatch
/// <summary>Returns instance of <typepsaramref name="TService"/> type.</summary>
/// <typeparam name="TService">The type of the requested service.</typeparam>
/// <returns>The requested service instance.</returns>
[MethodImpl(MethodImplHints.AggressingInlining)]
public TService Resolve<TService>()
{
return (TService)Resolve(typeof(TService));
}
/// <summary>Resolves default (non-keyed) service from container and returns created service object.</summary>
/// <param name="serviceType">Service type to search and to return.</param>
/// <returns>The requested service instance.</returns>
[MethodImpl(MethodImplHints.AggressingInlining)]
public object Resolve(Type serviceType)
{
var factoryDelegate = _defaultFactoryDelegateCache.Value.GetValueOrDefault(serviceType);
return factoryDelegate != null
? factoryDelegate(null, _thisContainerWeakRef, null)
: ResolveAndCacheDefaultDelegate(serviceType, false, null);
}
#endregion
#region IResolver
[MethodImpl(MethodImplHints.AggressingInlining)]
object IResolver.Resolve(Type serviceType, bool ifUnresolvedReturnDefault)
{
var factoryDelegate = _defaultFactoryDelegateCache.Value.GetValueOrDefault(serviceType);
return factoryDelegate != null
? factoryDelegate(null, _thisContainerWeakRef, null)
: ResolveAndCacheDefaultDelegate(serviceType, ifUnresolvedReturnDefault, null);
}
object IResolver.Resolve(Type serviceType, object serviceKey, bool ifUnresolvedReturnDefault, Type requiredServiceType, RequestInfo preResolveParent,
IScope scope)
{
preResolveParent = preResolveParent ?? RequestInfo.Empty;
var cacheEntryKey = serviceKey == null
? (object)serviceType
: new KV<object, object>(serviceType, serviceKey);
object cacheContextKey = requiredServiceType;
if (!preResolveParent.IsEmpty)
cacheContextKey = cacheContextKey == null
? (object)preResolveParent
: KV.Of(cacheContextKey, preResolveParent);
// Check cache first:
var registry = _registry.Value;
var cacheRef = registry.KeyedFactoryDelegateCache;
var cacheEntry = cacheRef.Value.GetValueOrDefault(cacheEntryKey);
if (cacheEntry != null)
{
var cachedFactoryDelegate = cacheContextKey == null
? cacheEntry.Key
: (cacheEntry.Value ?? ImTreeMap<object, FactoryDelegate>.Empty).GetValueOrDefault(cacheContextKey);
if (cachedFactoryDelegate != null)
return cachedFactoryDelegate(null, _thisContainerWeakRef, scope);
}
// Cache is missed, so get the factory and put it into cache:
ThrowIfContainerDisposed();
var ifUnresolved = ifUnresolvedReturnDefault ? IfUnresolved.ReturnDefault : IfUnresolved.Throw;
var request = Request.Create(this, serviceType, serviceKey, ifUnresolved, requiredServiceType, scope,
preResolveParent);
var factory = ((IContainer)this).ResolveFactory(request);
// Hack: may mutate (set) not null request service key.
if (serviceKey == null && request.ServiceKey != null)
cacheEntryKey = new KV<object, object>(serviceType, request.ServiceKey);
if (factory == null)
return null;
var factoryDelegate = factory.GetDelegateOrDefault(request);
if (factoryDelegate == null)
return null;
var service = factoryDelegate(null, _thisContainerWeakRef, scope);
if (registry.Services.IsEmpty)
return service;
// Cache factory only when we successfully called the factory delegate, to prevent failing delegates to be cached.
// Additionally disable caching when:
// no services registered, so the service probably empty collection wrapper or alike.
var cachedContextFactories =
(cacheEntry == null ? null : cacheEntry.Value) ??
ImTreeMap<object, FactoryDelegate>.Empty;
if (cacheContextKey == null)
cacheEntry = KV.Of(factoryDelegate, cachedContextFactories);
else
cacheEntry = KV.Of(cacheEntry == null ? null : cacheEntry.Key,
cachedContextFactories.AddOrUpdate(cacheContextKey, factoryDelegate));
var cacheVal = cacheRef.Value;
if (!cacheRef.TrySwapIfStillCurrent(cacheVal, cacheVal.AddOrUpdate(cacheEntryKey, cacheEntry)))
cacheRef.Swap(_ => _.AddOrUpdate(cacheEntryKey, cacheEntry));
return service;
}
private object ResolveAndCacheDefaultDelegate(Type serviceType, bool ifUnresolvedReturnDefault, IScope scope)
{
ThrowIfContainerDisposed();
var ifUnresolved = ifUnresolvedReturnDefault ? IfUnresolved.ReturnDefault : IfUnresolved.Throw;
var request = Request.Create(this, serviceType, ifUnresolved: ifUnresolved, scope: scope);
var factory = ((IContainer)this).ResolveFactory(request); // HACK: may mutate request, but it should be safe
// The situation is possible for multiple default services registered.
if (request.ServiceKey != null)
return ((IResolver)this).Resolve(serviceType, request.ServiceKey, ifUnresolvedReturnDefault, null, null, scope);
var factoryDelegate = factory == null ? null : factory.GetDelegateOrDefault(request);
if (factoryDelegate == null)
return null;
var registryValue = _registry.Value;
var service = factoryDelegate(null, _thisContainerWeakRef, scope);
// Additionally disable caching when:
// no services registered, so the service probably empty collection wrapper or alike.
if (!registryValue.Services.IsEmpty)
{
var cacheRef = registryValue.DefaultFactoryDelegateCache;
var cacheVal = cacheRef.Value;
if (!cacheRef.TrySwapIfStillCurrent(cacheVal, cacheVal.AddOrUpdate(serviceType, factoryDelegate)))
cacheRef.Swap(_ => _.AddOrUpdate(serviceType, factoryDelegate));
}
return service;
}
// todo: v3: remove unused composite key and required type parameters
IEnumerable<object> IResolver.ResolveMany(
Type serviceType, object serviceKey, Type requiredServiceType,
object compositeParentKey, Type compositeParentRequiredType,
RequestInfo preResolveParent, IScope scope)
{
var requiredItemType = requiredServiceType ?? serviceType;
// Emulating the collection parent so that collection related rules and conditions were applied
// the same way as if resolving IEnumerable<T>
if (preResolveParent == null || preResolveParent.IsEmpty)
preResolveParent = RequestInfo.Empty.Push(
typeof(IEnumerable<object>), requiredItemType, serviceKey, IfUnresolved.Throw,
0, FactoryType.Wrapper, implementationType: null, reuse: null, flags: RequestFlags.IsServiceCollection);
var container = (IContainer)this;
var items = container.GetAllServiceFactories(requiredItemType);
IEnumerable<ServiceRegistrationInfo> openGenericItems = null;
if (requiredItemType.IsClosedGeneric())
{
var requiredItemOpenGenericType = requiredItemType.GetGenericDefinitionOrNull();
openGenericItems = container.GetAllServiceFactories(requiredItemOpenGenericType)
.Select(x => new ServiceRegistrationInfo(x.Value, requiredItemOpenGenericType, x.Key));
}
// Append registered generic types with compatible variance,
// e.g. for IHandler<in E> - IHandler<A> is compatible with IHandler<B> if B : A.
IEnumerable<ServiceRegistrationInfo> variantGenericItems = null;
if (requiredItemType.IsGeneric() && container.Rules.VariantGenericTypesInResolvedCollection)
variantGenericItems = container.GetServiceRegistrations()
.Where(x => x.ServiceType.IsGeneric()
&& x.ServiceType.GetGenericTypeDefinition() == requiredItemType.GetGenericTypeDefinition()
&& x.ServiceType != requiredItemType
&& x.ServiceType.IsAssignableTo(requiredItemType));
if (serviceKey != null) // include only single item matching key.
{
items = items.Where(it => serviceKey.Equals(it.Key));
if (openGenericItems != null)
openGenericItems = openGenericItems.Where(it => serviceKey.Equals(it.OptionalServiceKey));
if (variantGenericItems != null)
variantGenericItems = variantGenericItems.Where(it => serviceKey.Equals(it.OptionalServiceKey));
}
var metadataKey = preResolveParent.MetadataKey;
var metadata = preResolveParent.Metadata;
if (metadataKey != null || metadata != null)
{
items = items.Where(it => it.Value.Setup.MatchesMetadata(metadataKey, metadata));
if (openGenericItems != null)
openGenericItems = openGenericItems.Where(it => it.Factory.Setup.MatchesMetadata(metadataKey, metadata));
if (variantGenericItems != null)
variantGenericItems = variantGenericItems.Where(it => it.Factory.Setup.MatchesMetadata(metadataKey, metadata));
}
// Exclude composite parent service from items, skip decorators
var parent = preResolveParent;
if (parent.FactoryType != FactoryType.Service)
parent = parent.Enumerate().FirstOrDefault(p => p.FactoryType == FactoryType.Service) ?? RequestInfo.Empty;
if (!parent.IsEmpty && parent.GetActualServiceType() == requiredItemType)
{
items = items.Where(x => x.Value.FactoryID != parent.FactoryID);
if (openGenericItems != null)
openGenericItems = openGenericItems.Where(x =>
!x.Factory.FactoryGenerator.GeneratedFactories.Enumerate().Any(f =>
f.Value.FactoryID == parent.FactoryID &&
f.Key.Key == parent.ServiceType && f.Key.Value == parent.ServiceKey));
if (variantGenericItems != null)
variantGenericItems = variantGenericItems.Where(x => x.Factory.FactoryID != parent.FactoryID);
}
foreach (var item in items)
{
var service = container.Resolve(serviceType, item.Key,
true, requiredServiceType, preResolveParent, scope);
if (service != null) // skip unresolved items
yield return service;
}
if (openGenericItems != null)
foreach (var item in openGenericItems)
{
var serviceKeyWithOpenGenericRequiredType = new[] { item.ServiceType, item.OptionalServiceKey };
var service = container.Resolve(serviceType, serviceKeyWithOpenGenericRequiredType,
true, requiredItemType, preResolveParent, scope);
if (service != null) // skip unresolved items
yield return service;
}
if (variantGenericItems != null)
foreach (var item in variantGenericItems)
{
var service = container.Resolve(serviceType, item.OptionalServiceKey,
true, item.ServiceType, preResolveParent, scope);
if (service != null) // skip unresolved items
yield return service;
}
var fallbackContainers = container.Rules.FallbackContainers;
if (!fallbackContainers.IsNullOrEmpty())
{
for (var i = 0; i < fallbackContainers.Length; i++)
{
var fallbackContainer = fallbackContainers[i];
var fallbackServices = fallbackContainer.Resolver.ResolveMany(serviceType,
serviceKey, requiredServiceType, compositeParentKey, compositeParentRequiredType,
preResolveParent, scope);
foreach (var fallbackService in fallbackServices)
yield return fallbackService;
}
}
}
private void ThrowIfContainerDisposed()
{
if (IsDisposed)
Throw.It(Error.ContainerIsDisposed);
}
#endregion
#region IScopeAccess
IScope IScopeAccess.GetCurrentScope()
{
return ((IScopeAccess)this).GetCurrentNamedScope(null, false);
}
/// <summary>Gets current scope matching the <paramref name="name"/>.
/// If name is null then current scope is returned, or if there is no current scope then exception thrown.</summary>
/// <param name="name">May be null</param> <param name="throwIfNotFound">Says to throw if no scope found.</param>
/// <returns>Found scope or throws exception.</returns>
/// <exception cref="ContainerException"> with code <see cref="Error.NoMatchedScopeFound"/>.</exception>
IScope IScopeAccess.GetCurrentNamedScope(object name, bool throwIfNotFound)
{
var currentScope = _scopeContext == null ? _openedScope : _scopeContext.GetCurrentOrDefault();
return currentScope == null
? (throwIfNotFound ? Throw.For<IScope>(Error.NoCurrentScope) : null)
: GetMatchingScopeOrDefault(currentScope, name)
?? (throwIfNotFound ? Throw.For<IScope>(Error.NoMatchedScopeFound, currentScope, name) : null);
}
private static IScope GetMatchingScopeOrDefault(IScope scope, object name)
{
if (name != null)
while (scope != null && !name.Equals(scope.Name))
scope = scope.Parent;
return scope;
}
// note: The method required for .NET 3.5 which does not have Expression.Assign, so the need for "ref" parameter (BTW "ref" is not supported in XAMARIN)
/// <summary>Check if scope is not null, then just returns it, otherwise will create and return it.</summary>
/// <param name="scope">May be null scope.</param>
/// <param name="serviceType">Marking scope with resolved service type.</param>
/// <param name="serviceKey">Marking scope with resolved service key.</param>
/// <returns>Input <paramref name="scope"/> ensuring it is not null.</returns>
IScope IScopeAccess.GetOrCreateResolutionScope(ref IScope scope, Type serviceType, object serviceKey)
{
return scope ?? (scope = new Scope(null, new KV<Type, object>(serviceType, serviceKey)));
}
/// <summary>Check if scope is not null, then just returns it, otherwise will create and return it.</summary>
/// <param name="scope">May be null scope.</param>
/// <param name="serviceType">Marking scope with resolved service type.</param>
/// <param name="serviceKey">Marking scope with resolved service key.</param>
/// <returns>Input <paramref name="scope"/> ensuring it is not null.</returns>
public IScope GetOrNewResolutionScope(IScope scope, Type serviceType, object serviceKey)
{
return scope ?? new Scope(null, new KV<Type, object>(serviceType, serviceKey));
}
/// <summary>If both <paramref name="assignableFromServiceType"/> and <paramref name="serviceKey"/> are null,
/// then returns input <paramref name="scope"/>.
/// Otherwise searches scope hierarchy to find first scope with: Type assignable <paramref name="assignableFromServiceType"/> and
/// Key equal to <paramref name="serviceKey"/>.</summary>
/// <param name="scope">Scope to start matching with Type and Key specified.</param>
/// <param name="assignableFromServiceType">Type to match.</param> <param name="serviceKey">Key to match.</param>
/// <param name="outermost">If true - commands to look for outermost match instead of nearest.</param>
/// <param name="throwIfNotFound">Says to throw if no scope found.</param>
/// <returns>Matching scope or throws <see cref="ContainerException"/>.</returns>
IScope IScopeAccess.GetMatchingResolutionScope(IScope scope, Type assignableFromServiceType, object serviceKey,
bool outermost, bool throwIfNotFound)
{
return FindMatchingResolutionScope(scope, assignableFromServiceType, serviceKey, outermost)
?? (!throwIfNotFound ? null
: Throw.For<IScope>(Error.NoMatchedScopeFound, scope, new KV<Type, object>(assignableFromServiceType, serviceKey)));
}
private static IScope FindMatchingResolutionScope(IScope scope, Type assignableFromServiceType, object serviceKey,
bool outermost)
{
if (assignableFromServiceType == null && serviceKey == null)
return scope;
IScope matchedScope = null;
while (scope != null)
{
var name = scope.Name as KV<Type, object>;
if (name != null && (
assignableFromServiceType == null ||
name.Key.IsAssignableTo(assignableFromServiceType) ||
assignableFromServiceType.IsOpenGeneric() &&
name.Key.GetGenericDefinitionOrNull().IsAssignableTo(assignableFromServiceType)) &&
(serviceKey == null || serviceKey.Equals(name.Value)))
{
matchedScope = scope;
if (!outermost) // break on first found match.
break;
}
scope = scope.Parent;
}
return matchedScope;
}
#endregion
#region IContainer
/// <summary>The rules object defines policies per container for registration and resolution.</summary>
public Rules Rules { get; private set; }
/// <summary>Indicates that container is disposed.</summary>
public bool IsDisposed
{
get { return _disposed == 1 || _singletonScope.IsDisposed; }
}
// todo: v3: remove
/// <summary>Obsolete: replaced with <see cref="Request.Create"/>/.</summary>
Request IContainer.EmptyRequest
{
get { return Request.CreateEmpty(this); }
}
// todo: v3: Rename to ResolverContext
/// <summary>Self weak reference, with readable message when container is GCed/Disposed.</summary>
ContainerWeakRef IContainer.ContainerWeakRef
{
get { return _thisContainerWeakRef; }
}
Factory IContainer.ResolveFactory(Request request)
{
var factory = GetServiceFactoryOrDefault(request, Rules.FactorySelector);
if (factory == null)
{
factory = WrappersSupport.ResolveWrapperOrGetDefault(request);
if (factory == null && !Rules.FallbackContainers.IsNullOrEmpty())
factory = ResolveFromFallbackContainers(Rules.FallbackContainers, request);
if (factory == null && !Rules.UnknownServiceResolvers.IsNullOrEmpty())
for (var i = 0; factory == null && i < Rules.UnknownServiceResolvers.Length; i++)
factory = Rules.UnknownServiceResolvers[i](request);
}
if (factory != null && factory.FactoryGenerator != null)
factory = factory.FactoryGenerator.GetGeneratedFactory(request);
if (factory == null && request.IfUnresolved == IfUnresolved.Throw)
ThrowUnableToResolve(request);
return factory;
}
private static Factory ResolveFromFallbackContainers(ContainerWeakRef[] fallbackContainers, Request request)
{
var container = request.Container;
for (var i = 0; i < fallbackContainers.Length; i++)
{
var containerWeakRef = fallbackContainers[i];
var containerRequest = request.WithNewContainer(containerWeakRef);
// Continue to next parent if factory is not found in first parent by
// updating IfUnresolved policy to ReturnDefault.
if (containerRequest.IfUnresolved == IfUnresolved.Throw)
containerRequest = containerRequest.WithChangedServiceInfo(info => // todo: v3: review and remove
ServiceInfo.Of(info.ServiceType, IfUnresolved.ReturnDefault)
.InheritInfoFromDependencyOwner(info, container: container));
var factory = containerWeakRef.Container.ResolveFactory(containerRequest);
if (factory != null)
return factory;
}
return null;
}
internal static void ThrowUnableToResolve(Request request)
{
var container = request.Container;
var registrations = container
.GetAllServiceFactories(request.ServiceType, bothClosedAndOpenGenerics: true)
.Aggregate(new StringBuilder(), (s, f) =>
(f.Value.HasMatchingReuseScope(request)
? s.Append(" ")
: s.Append(" without matching scope "))
.AppendLine(f.ToString()));
if (registrations.Length != 0)
Throw.It(Error.UnableToResolveFromRegisteredServices, request,
request.Scopes.GetCurrentScope(), request.Scope, registrations);
else
Throw.It(Error.UnableToResolveUnknownService, request,
container.Rules.FallbackContainers.EmptyIfNull().Length,
container.Rules.UnknownServiceResolvers.EmptyIfNull().Length);
}
Factory IContainer.GetServiceFactoryOrDefault(Request request)
{
return GetServiceFactoryOrDefault(request, Rules.FactorySelector);
}
IEnumerable<KV<object, Factory>> IContainer.GetAllServiceFactories(Type serviceType, bool bothClosedAndOpenGenerics)
{
var serviceFactories = _registry.Value.Services;
var entry = serviceFactories.GetValueOrDefault(serviceType);
var factories = GetRegistryEntryKeyFactoryPairs(entry);
if (bothClosedAndOpenGenerics && serviceType.IsClosedGeneric())
{
var openGenericEntry = serviceFactories.GetValueOrDefault(serviceType.GetGenericTypeDefinition());
if (openGenericEntry != null)
factories = factories.Concat(GetRegistryEntryKeyFactoryPairs(openGenericEntry));
}
var dynamicRegistrationProviders = Rules.DynamicRegistrationProviders;
if (!dynamicRegistrationProviders.IsNullOrEmpty())
{
for (var i = 0; i < dynamicRegistrationProviders.Length; i++)
{
var provider = dynamicRegistrationProviders[i];
var dynamicFactories = provider(serviceType, null, FactoryType.Service);
// todo: Do I need to filter for FactoryType.Service?
if (dynamicFactories != null)
factories = factories.Concat(dynamicFactories);
}
}
return factories;
}
private static IEnumerable<KV<object, Factory>> GetRegistryEntryKeyFactoryPairs(object entry)
{
return entry == null ? Enumerable.Empty<KV<object, Factory>>()
: entry is Factory ? new[] { new KV<object, Factory>(DefaultKey.Value, (Factory)entry) }
: ((FactoriesEntry)entry).Factories.Enumerate();
}
Expression IContainer.GetDecoratorExpressionOrDefault(Request request)
{
// return early if no decorators registered and no fallback containers to provide them
if (_registry.Value.Decorators.IsEmpty &&
request.Rules.FallbackContainers.IsNullOrEmpty())
return null;
var arrayElementType = request.ServiceType.GetArrayElementTypeOrNull();
if (arrayElementType != null)
request = request.WithChangedServiceInfo(info => info
.With(typeof(IEnumerable<>).MakeGenericType(arrayElementType)));
// Define the list of ids for the already applied decorators
int[] appliedDecoratorIDs = null;