-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmartDIContainer.cs
1445 lines (1299 loc) · 63.1 KB
/
SmartDIContainer.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
// *********************************************************************************
// Copyright @2021 Marcus Technical Services, Inc.
// <copyright
// file=SmartDIContainer.cs
// company="Marcus Technical Services, Inc.">
// </copyright>
//
// MIT License
//
// 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 NON-INFRINGEMENT. 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 Com.MarcusTS.SmartDI
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Com.MarcusTS.SharedUtils.Utils;
/// <summary>
/// Enum StorageRules
/// </summary>
public enum StorageRules
{
/// <summary>
/// Default for class management; instantiates but does not store.
/// </summary>
/// <summary>
/// Any access level
/// </summary>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for AnyAccessLevel
AnyAccessLevel,
/// <summary>
/// Requires one or more companion "parents"; once all shared parents are gone, the stored instance is removed.
/// </summary>
/// <summary>
/// The shared dependency between instances
/// </summary>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for SharedDependencyBetweenInstances
SharedDependencyBetweenInstances,
/// <summary>
/// Is stored once requested, and thereafter remains in memory for the life of the container.
/// </summary>
/// <summary>
/// The global singleton
/// </summary>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for GlobalSingleton
GlobalSingleton,
/// <summary>
/// The instance is not stored after Resolve.
/// In the "any" case, the resolver can ask for AnyAccessLevel and can then resolve as Any, Shared, or Singleton without
/// error.
/// In this case, the resolver *must* ask for DoNotStore as the requested access level.
/// Use this access level if you are 100% certain that you never want to store the type as registered.
/// </summary>
/// <summary>
/// The do not store
/// </summary>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for DoNotStore
DoNotStore
}
/// <summary>
/// Interface ISmartDIContainer
/// Implements the <see cref="System.IDisposable" />
/// </summary>
/// <seealso cref="System.IDisposable" />
/// <seealso cref="System.IDisposable" />
/// <seealso cref="System.IDisposable" />
public interface ISmartDIContainer : IDisposable
{
/// <summary>
/// Ignores (will not act upon) errors as long as true. NOTE the special case for <see cref="IgnoreResolveError" />
/// below, which can override this setting./>
/// </summary>
/// <value><c>true</c> if [ignore all errors]; otherwise, <c>false</c>.</value>
/// <summary>
/// Gets or sets a value indicating whether [ignore all errors].
/// </summary>
/// <value><c>true</c> if [ignore all errors]; otherwise, <c>false</c>.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for IgnoreAllErrors
bool IgnoreAllErrors { get; set; }
/// <summary>
/// Ignores (will not act upon) a resolve error as long as true.
/// </summary>
/// <value><c>true</c> if [ignore resolve errors]; otherwise, <c>false</c>.</value>
/// <summary>
/// Gets or sets a value indicating whether [ignore resolve error].
/// </summary>
/// <value><c>true</c> if [ignore resolve error]; otherwise, <c>false</c>.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for IgnoreResolveError
bool IgnoreResolveError { get; set; }
/// <summary>
/// Called by the deriver whenever a class is about to disappear from view. It is better to call this before the
/// finalizer, as that can be extremely late. An example would be Xamarin.Forms.ContentPage.OnDisappearing. Other
/// views or view models will have to listen to the original page event and then notify about their own demise. If
/// this step is skipped, none of the lifecycle protections will occur!
/// </summary>
/// <param name="containerObj">The container object.</param>
/// <summary>
/// Containers the object is disappearing.
/// </summary>
/// <param name="containerObj">The container object.</param>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for ContainerObjectIsDisappearing
void ContainerObjectIsDisappearing(object containerObj);
/// <summary>
/// Determine of a qualifying registration exists for a given type.
/// Could be used as a pre-tst before Resolve() if confusion exists as to the safety.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns><c>true</c> if a qualifying registration exits, else <c>false</c>.</returns>
/// <summary>
/// Qualifyings the registrations exist.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for QualifyingRegistrationsExist`1
bool QualifyingRegistrationsExist<T>();
/// <summary>
/// Determine of a qualifying registration exists for a given type.
/// Could be used as a pre-tst before Resolve() if confusion exists as to the safety.
/// </summary>
/// <param name="type">The class type that would be instantiated by the qualifying registration.</param>
/// <returns><c>true</c> if a qualifying registration exits, else <c>false</c>.</returns>
/// <summary>
/// Qualifyings the registrations exist.
/// </summary>
/// <param name="type">The type.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for QualifyingRegistrationsExist
bool QualifyingRegistrationsExist(Type type);
/// <summary>
/// Adds a list of types that the type can be resolved as. Includes creators and storage rules.
/// </summary>
/// <param name="classT">The class type that owns the contracts.</param>
/// <param name="creatorsAndRules">The list of class creators and rules. The creators can be null.</param>
/// <summary>
/// Registers the type contracts.
/// </summary>
/// <param name="classT">The class t.</param>
/// <param name="creatorsAndRules">The creators and rules.</param>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for RegisterTypeContracts
void RegisterTypeContracts
(
Type classT,
IDictionary<Type, IProvideCreatorAndStorageRule> creatorsAndRules
);
/// <summary>
/// Creates an instance of a class and stores it according to the requested rules. Only works if you have
/// registered each base class first along with any interface they should be available (type-cast) as. See
/// <see cref="RegisterTypeContracts" /> for details about this.
/// </summary>
/// <param name="typeRequestedT">
/// This is the type that you wish to receive. It is not necessarily the "base" class type. It is more commonly an
/// interface implemented by your base class type.
/// </param>
/// <param name="storageRule">
/// This is a *request* for a storage rule, but is subject to strict guidelines:
/// * If you ask for "AnyAccessLevel", and there is no other value set in the registration, we will give you an
/// unstored local variable.
/// * If, when you registered, you set the access level to something like "SharedDependencyBetweenInstances", and
/// then here on Resolve ask for "GlobalSingleton", we default to throw with an illegal request.
/// </param>
/// <param name="boundInstance">
/// The "host" or "bound" class that is attached to this instance. Only required if you need a
/// "SharedDependencyBetweenInstances".
/// </param>
/// <param name="conflictResolver">
/// This is an advanced parameter where you can include a function to "break the tie" when this container tries to
/// Resolve, but comes up with more than one competing resolution contract. If you leave this at null, and we
/// cannot see a single legal choice, we will throw an error.
/// </param>
/// <returns>An object which *must* then be cast as the type requested by the *caller*.</returns>
/// <summary>
/// Resolves the specified type requested t.
/// </summary>
/// <param name="typeRequestedT">The type requested t.</param>
/// <param name="storageRule">The storage rule.</param>
/// <param name="boundInstance">The bound instance.</param>
/// <param name="conflictResolver">The conflict resolver.</param>
/// <returns>System.Object.</returns>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for Resolve
object Resolve
(
Type typeRequestedT,
StorageRules storageRule = StorageRules.AnyAccessLevel,
object boundInstance = null,
Func<ConcurrentDictionary<Type, ITimeStampedCreatorAndStorageRules>, IConflictResolution>
conflictResolver =
null
);
/// <summary>
/// Removes a list of types that the parent type can be resolved as. Includes creators and storage rules.
/// </summary>
/// <typeparam name="TParent">The generic parent type</typeparam>
/// <param name="typesToUnregister">The types to remove.</param>
/// <summary>
/// Unregisters the type contracts.
/// </summary>
/// <typeparam name="TParent">The type of the t parent.</typeparam>
/// <param name="typesToUnregister">The types to unregister.</param>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for UnregisterTypeContracts`1
void UnregisterTypeContracts<TParent>(params Type[] typesToUnregister);
}
/// <summary>
/// Class SmartDIContainer.
/// Implements the <see cref="ISmartDIContainer" />
/// Implements the <see cref="Com.MarcusTS.SmartDI.ISmartDIContainer" />
/// </summary>
/// <seealso cref="Com.MarcusTS.SmartDI.ISmartDIContainer" />
/// <seealso cref="ISmartDIContainer" />
/// <seealso cref="Com.MarcusTS.SmartDI.ISmartDIContainer" />
/// <seealso cref="Com.MarcusTS.SmartDI.ISmartDIContainer" />
public class SmartDIContainer : ISmartDIContainer
{
/// <summary>
/// A dictionary of global singletons keyed by type. There can only be one each of a given type.
/// </summary>
/// <summary>
/// The global singletons by type
/// </summary>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for _globalSingletonsByType
protected readonly IDictionary<Type, object> _globalSingletonsByType = new ConcurrentDictionary<Type, object>();
/// <summary>
/// Specifies that a type can be resolved as a specific type (can be different as long as
/// related) Also sets the storage rules. Defaults to "all".
/// </summary>
/// <summary>
/// The registered type contracts
/// </summary>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for _registeredTypeContracts
protected readonly IDictionary<Type, ITimeStampedCreatorAndStorageRules> _registeredTypeContracts =
new ConcurrentDictionary<Type, ITimeStampedCreatorAndStorageRules>();
/// <summary>
/// A dictionary of instances that are shared between one ore more other instances. When the list of shared
/// instances reaches zero, the main instance is removed.
/// </summary>
/// <summary>
/// The shared instances with bound members
/// </summary>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for _sharedInstancesWithBoundMembers
protected readonly IDictionary<object, List<object>> _sharedInstancesWithBoundMembers =
new ConcurrentDictionary<object, List<object>>();
/// <summary>
/// Initializes a new instance of the <see cref="SmartDIContainer" /> class.
/// </summary>
/// <param name="throwOnMultipleRegisteredTypesForOneResolvedType">
/// if set to <c>true</c> [throw on multiple registered
/// types for one resolved type].
/// </param>
/// <param name="throwOnAttemptToAssignDuplicateContractSubType">
/// if set to <c>true</c> [throw on attempt to assign
/// duplicate contract sub type].
/// </param>
/// <summary>
/// Initializes a new instance of the <see cref="SmartDIContainer" /> class.
/// </summary>
/// <param name="throwOnMultipleRegisteredTypesForOneResolvedType">
/// if set to <c>true</c> [throw on multiple registered
/// types for one resolved type].
/// </param>
/// <param name="throwOnAttemptToAssignDuplicateContractSubType">
/// if set to <c>true</c> [throw on attempt to assign
/// duplicate contract sub type].
/// </param>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for #ctor
public SmartDIContainer
(
bool throwOnMultipleRegisteredTypesForOneResolvedType = false,
bool throwOnAttemptToAssignDuplicateContractSubType = false
)
{
ThrowOnMultipleRegisteredTypesForOneResolvedType = throwOnMultipleRegisteredTypesForOneResolvedType;
ThrowOnAttemptToAssignDuplicateContractSubType = throwOnAttemptToAssignDuplicateContractSubType;
}
/// <summary>
/// Gets the is argument exception thrown.
/// </summary>
/// <value>The is argument exception thrown.</value>
/// <summary>
/// Gets the is argument exception thrown.
/// </summary>
/// <value>The is argument exception thrown.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for IsArgumentExceptionThrown
protected string IsArgumentExceptionThrown { get; private set; }
/// <summary>
/// Gets the is operation exception thrown.
/// </summary>
/// <value>The is operation exception thrown.</value>
/// <summary>
/// Gets the is operation exception thrown.
/// </summary>
/// <value>The is operation exception thrown.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for IsOperationExceptionThrown
protected string IsOperationExceptionThrown { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is unit testing.
/// </summary>
/// <value><c>true</c> if this instance is unit testing, else <c>false</c>.</value>
/// <summary>
/// Gets or sets a value indicating whether this instance is unit testing.
/// </summary>
/// <value><c>true</c> if this instance is unit testing; otherwise, <c>false</c>.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for IsUnitTesting
protected bool IsUnitTesting { get; set; }
/// <summary>
/// If a user registers a contract like this: _container.RegisterType{SimpleClass}(StorageRules.DoNotStore, null,
/// false, typeof(IAmSimple)); _container.RegisterType{SimpleClass}(StorageRules.GlobalSingleton, null, false,
/// typeof(IAmSimple)); ... we have to save the second registration on top of the first one. Only one sub-type can
/// exist with a single storage level. With this Boolean set to false (default), we will casually over-write the
/// most recent entry on top of the old entry. With the value set to True, we will throw an error upon over-writing
/// any existing registration.
/// </summary>
/// <value><c>true</c> if [throw on attempt to assign duplicate contract sub type], else <c>false</c>.</value>
/// <summary>
/// Gets or sets a value indicating whether [throw on attempt to assign duplicate contract sub type].
/// </summary>
/// <value><c>true</c> if [throw on attempt to assign duplicate contract sub type]; otherwise, <c>false</c>.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for ThrowOnAttemptToAssignDuplicateContractSubType
protected bool ThrowOnAttemptToAssignDuplicateContractSubType { get; set; }
/// <summary>
/// Registrations occur for base class types. They are usually delivered as interface types. We expect that when
/// you register an interface for Resolve, you will only have one interface for a given base class type.
/// So in this example:
/// RegisterType(Class1, Interface1)
/// You would not also create:
/// RegisterType(Class2, Interface1)
/// This is considered to be unsafe because it is not clear or purposeful, and the container cannot make a refined
/// judgment with any known rules.
/// If this Boolean is set to True, we will throw an error if we come across such a condition.
/// To avoid the error, leave the Boolean at false, where it defaults.
/// With the setting false, we will just pick the first available candidate.
/// THIS IS SLOPPY... so try to set this Boolean to True and make careful registrations.
/// </summary>
/// <value><c>true</c> if [throw on multiple registered types for one resolved type], else <c>false</c>.</value>
/// <summary>
/// Gets or sets a value indicating whether [throw on multiple registered types for one resolved type].
/// </summary>
/// <value><c>true</c> if [throw on multiple registered types for one resolved type]; otherwise, <c>false</c>.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for ThrowOnMultipleRegisteredTypesForOneResolvedType
protected bool ThrowOnMultipleRegisteredTypesForOneResolvedType { get; set; }
/// <summary>
/// Ignores (will not act upon) errors as long as true.
/// </summary>
/// <value><c>true</c> if [ignore all errors]; otherwise, <c>false</c>.</value>
/// <summary>
/// Ignores (will not act upon) errors as long as true. NOTE the special case for <see cref="IgnoreResolveError" />
/// below, which can override this setting./>
/// </summary>
/// <value><c>true</c> if [ignore all errors]; otherwise, <c>false</c>.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for IgnoreAllErrors
public bool IgnoreAllErrors { get; set; }
/// <summary>
/// Ignores (will not act upon) a resolve error as long as true.
/// </summary>
/// <value><c>true</c> if [ignore resolve errors]; otherwise, <c>false</c>.</value>
/// <summary>
/// Ignores (will not act upon) a resolve error as long as true.
/// </summary>
/// <value><c>true</c> if [ignore resolve errors]; otherwise, <c>false</c>.</value>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for IgnoreResolveError
public bool IgnoreResolveError { get; set; }
/// <summary>
/// Called by the deriver whenever a class is about to disappear from view. It is better to call this before the
/// finalizer, as that can be extremely late. An example would be Xamarin.Forms.ContentPage.OnDisappearing. Other
/// views or view models will have to listen to the original page event and then notify about their own demise. If
/// this step is skipped, none of the lifecycle protections will occur!
/// </summary>
/// <param name="containerObj">A variable that was inserted into the container "live" and is now being deactivated.</param>
/// <summary>
/// Called by the deriver whenever a class is about to disappear from view. It is better to call this before the
/// finalizer, as that can be extremely late. An example would be Xamarin.Forms.ContentPage.OnDisappearing. Other
/// views or view models will have to listen to the original page event and then notify about their own demise. If
/// this step is skipped, none of the lifecycle protections will occur!
/// </summary>
/// <param name="containerObj">The container object.</param>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for ContainerObjectIsDisappearing
public virtual void ContainerObjectIsDisappearing(object containerObj)
{
// Remove the class from the global singletons
RemoveSingletonInstance(containerObj.GetType());
// See if the shared instances contain the class. There are two possible scenarios:
// 1. This class is the shared class. If so, we remove the entire node that contains the container class.
// This only removes the object if it exists (its type is registered).
RemoveSharedInstance(containerObj.GetType());
// 2. This class is bound to a shared class. If true, we remove that single part of the node. However, if this
// is the last node, then we do as with #1 -- we kill the entire node.
RemoveBoundSharedDependencies(containerObj);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for Dispose
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Determine of a qualifying registration exists for a given type.
/// Could be used as a pre-tst before Resolve() if confusion exists as to the safety.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns><c>true</c> if a qualifying registration exits, else <c>false</c>.</returns>
/// <summary>
/// Determine of a qualifying registration exists for a given type.
/// Could be used as a pre-tst before Resolve() if confusion exists as to the safety.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns><c>true</c> if a qualifying registration exits, else <c>false</c>.</returns>
/// <autogeneratedoc />
/// TODO Edit XML Comment Template for QualifyingRegistrationsExist`1
public bool QualifyingRegistrationsExist<T>()
{
return QualifyingRegistrationsExist(typeof(T));
}
/// <summary>
/// Determine of a qualifying registration exists for a given type.
/// Could be used as a pre-tst before Resolve() if confusion exists as to the safety.
/// </summary>
/// <param name="type">The class type that would be instantiated by the qualifying registration.</param>
/// <returns><c>true</c> if a qualifying registration exits, else <c>false</c>.</returns>
public bool QualifyingRegistrationsExist(Type type)
{
return GetQualifyingRegistrations(type).IsNotEmpty();
}
/// <summary>
/// Adds a list of types that the type can be resolved as. Includes creators and storage rules.
/// </summary>
/// <param name="classT">The base type for the class rule.</param>
/// <param name="creatorsAndRules">The list of class creators and rules. The creators can be null.</param>
public void RegisterTypeContracts
(
Type classT,
IDictionary<Type, IProvideCreatorAndStorageRule> creatorsAndRules
)
{
// ClassT must be a standard public type -- otherwise, can't be instantiated
if (!classT.IsPublic || !classT.IsClass || classT.IsGenericType || classT.IsSealed || classT.IsAbstract ||
classT.IsInterface)
{
ThrowArgumentException(nameof(RegisterTypeContracts),
"Type ->" + classT + "<- must be a standard public type");
return;
}
// ClassT may or may not be included in the resolvable types.
// *However*, if there are no resolvable types (no 'creators and rules'), then we force ClassT to be resolvable by adding it here manually.
// Otherwise, this is a meaningless registration that will always fail.
if (creatorsAndRules.IsEmpty())
{
// Add the new rule as the only member - order "0"
creatorsAndRules = new ConcurrentDictionary<Type, IProvideCreatorAndStorageRule>();
creatorsAndRules.Add(classT, new CreatorAndStorageRule());
}
else
{
// Interrogate the creatorsAdRules to make sure that all requested types can indeed be cast from classT.
foreach (var creatorAndRule in creatorsAndRules)
{
if (!classT.IsTypeOrAssignableFromType(creatorAndRule.Key))
{
ThrowArgumentException(nameof(RegisterTypeContracts),
"Type ->" + classT + "<- cannot be cast as ->" +
creatorAndRule.Key);
return;
}
}
}
// Are there other registrants that already return/resolve the any of the same classes as we do in our creators
// and rules? If so, is it their master type the same as us (probably not unless we have duplicated this
// registration exactly)?
var creatorsAndRulesTypes = creatorsAndRules.Keys;
var competingContracts = _registeredTypeContracts
.Where(rc => (rc.Key != classT) && creatorsAndRulesTypes
.Intersect(rc.Value.CreatorsAndStorageRules.Keys)
.Any())
.ToList();
// If there is more than one master type, we should consider throwing, as this is extremely confusing for resolution.
if (competingContracts.Any())
{
if (ThrowOnMultipleRegisteredTypesForOneResolvedType)
{
ThrowArgumentException(nameof(RegisterTypeContracts),
"Cannot register a second contract when the property ->" +
nameof(ThrowOnMultipleRegisteredTypesForOneResolvedType) +
"< is true. The competing contract is of type ->" +
competingContracts +
"<-");
return;
}
}
// All is good, so register
// If the contract does not exist, add it and block-copy in the entire list of creators and rules
if (!_registeredTypeContracts.ContainsKey(classT))
{
_registeredTypeContracts.Add(classT,
new TimeStampedCreatorAndStorageRules
{ WhenAdded = DateTime.Now, CreatorsAndStorageRules = creatorsAndRules });
}
else
{
// Return the value to the array
_registeredTypeContracts[classT] = SeekExistingContract(classT, creatorsAndRules);
}
}
/// <summary>
/// Fetches an object of the requested type.
/// If the object does not exist, creates it.
/// In certain cases, stores the object.
/// </summary>
/// <param name="typeRequestedT">The type to cast the object as. NOTE that the programmer does this after their Resolve.</param>
/// <param name="ruleRequested">The sort of storage rule to use in managing the resolved object.</param>
/// <param name="boundParent">
/// If the storage rule is <see cref="StorageRules.SharedDependencyBetweenInstances" />,
/// this is the object that will share the resolved object with other peers.
/// </param>
/// <param name="conflictResolver">
/// If supplied, determines which competing resolution will be returned for the type
/// requested.
/// </param>
/// <returns>System.Object.</returns>
public object Resolve
(
Type typeRequestedT,
StorageRules ruleRequested = StorageRules.AnyAccessLevel,
object boundParent = null,
Func<ConcurrentDictionary<Type, ITimeStampedCreatorAndStorageRules>, IConflictResolution>
conflictResolver =
null
)
{
var qualifyingRegistrations = GetQualifyingRegistrations(typeRequestedT);
if (qualifyingRegistrations.IsEmpty())
{
ThrowArgumentException(nameof(Resolve), "No registered contracts for the type " + typeRequestedT, true);
return null;
}
// We have at least one qualifying registration.
// Filter against storage rules.
// If the qualifying registration is 'any', then any requested storage works.
// If the requested storage rule is 'any', that also works.
// Otherwise, the qualifying registration storage rule and the requested storage rule *must* match.
if (ruleRequested != StorageRules.AnyAccessLevel)
{
// The rules qualify if they are "all" or if they match the requested rule.
var storageMatchedQualifyingRegistrations =
new ConcurrentDictionary<Type, ITimeStampedCreatorAndStorageRules>(
qualifyingRegistrations.Where(qr =>
(qr.Value.CreatorsAndStorageRules[typeRequestedT]
.ProvidedStorageRule == StorageRules.AnyAccessLevel) ||
(qr.Value.CreatorsAndStorageRules[typeRequestedT]
.ProvidedStorageRule == ruleRequested)));
if (storageMatchedQualifyingRegistrations.IsEmpty())
{
ThrowArgumentException(nameof(Resolve), "Cannot find a registration for the type ->" +
typeRequestedT +
"<- using storage rule ->" +
ruleRequested + "<-",
true);
return null;
}
// Return this value to the original collection.
qualifyingRegistrations = storageMatchedQualifyingRegistrations;
}
if (!qualifyingRegistrations.Any())
{
ThrowArgumentException(nameof(Resolve),
"Cannot find a registration for the type ->" + typeRequestedT + "<-");
return null;
}
var resolutionToSeek = default(KeyValuePair<Type, IProvideCreatorAndStorageRule>);
// Will need to determine the type we are creating (not the typeRequestedT that the user will cast this as)
var qualifyingMasterType = default(Type);
// If more than one registration, see if we can decide with the conflict resolver
if (CannotResolveConflicts(conflictResolver, qualifyingRegistrations, ref qualifyingMasterType,
ref resolutionToSeek))
{
ThrowOperationException(nameof(Resolve), "Cannot determine which one of " +
qualifyingRegistrations.Count +
" registrations to use through the provided conflict resolver.");
return null;
}
// If no resolutionToSeek yet (steps above failed), find it through another means.
if (resolutionToSeek.IsAnEqualObjectTo(default(KeyValuePair<Type, IProvideCreatorAndStorageRule>)))
{
// Unconditional; applies to any count for qualifyingRegistrations
if (CannotFindObviousChoice(typeRequestedT, qualifyingRegistrations, ref resolutionToSeek))
{
ThrowArgumentException(nameof(Resolve),
"Unexpected error fetching a known contract for the type " + typeRequestedT);
return null;
}
}
// If unset, set now
if (qualifyingMasterType.IsAnEqualObjectTo(default(Type)))
{
// Take the *first* qualifying registration made
qualifyingMasterType = qualifyingRegistrations.OrderBy(qr => qr.Value.WhenAdded).First().Key;
}
// The same as having no qualifying registrations. Should never occur based on the checks above.
if (resolutionToSeek.IsAnEqualObjectTo(default(KeyValuePair<Type, IProvideCreatorAndStorageRule>)))
{
ThrowArgumentException(nameof(Resolve), "Cannot find a registration for the type " + typeRequestedT);
return null;
}
// Verify that the result will be legal, since we will cast as TypeRequestedT
if (!qualifyingMasterType.IsTypeOrAssignableFromType(typeRequestedT))
{
ThrowOperationException(nameof(Resolve), "Cannot save an instance of ->" + qualifyingMasterType +
"<- as ->" + typeRequestedT + "<-");
return null;
}
// Now we have:
// 1. A master type to create;
// 2. A TypeRequestedT type to save as -- these might not be the same, but must relate class-design-wise
// 3. A resolution to seek that might include an instance creator;
// 4. If no instance creator, then we will use activator create instance
// We switch here; the resolutionToSeek now has authority over our process.
// This means that we also accept the resolutionToSeek's Type
var finalTypeRequestedT = resolutionToSeek.Key;
ruleRequested = resolutionToSeek.Value.ProvidedStorageRule;
// Verify that we do not have an incompatible rules request and bound object
if ((ruleRequested == StorageRules.SharedDependencyBetweenInstances) && (boundParent == null))
{
ThrowArgumentException(nameof(Resolve),
"Cannot resolve a shared type without a bound instance to attach it to. To share a variable without a bound instance, use a global singleton.");
return null;
}
if (ruleRequested == StorageRules.GlobalSingleton)
{
if (_globalSingletonsByType.ContainsKey(finalTypeRequestedT))
{
var foundGlobalInstance = _globalSingletonsByType[finalTypeRequestedT];
// If the instance is invalid -- which should not generally occur -- remove it.
if (foundGlobalInstance == null)
{
_globalSingletonsByType.Remove(finalTypeRequestedT);
}
// ELSE return it
else
{
return foundGlobalInstance;
}
}
// ELSE proceed to creating the instance
}
else if (ruleRequested == StorageRules.SharedDependencyBetweenInstances)
{
// There is a remote possibility that after being stored as a shared instance, they key will get garbage
// collected, making it null. This case is ignored because we cannot get its type, etc.
// NOTE that we ask for the qualifyingMasterType. That is what we add down below (see line 842,
// "_sharedInstancesWithBoundMembers.Add(sharedInstance, new List<object>(boundParents));" --
// the key, sharedInstance, is of type qualifyingMasterType.
var foundSharedInstances =
_sharedInstancesWithBoundMembers.FirstOrDefault(si =>
(si.Key != null) && (si.Key.GetType() ==
qualifyingMasterType));
// If valid (not empty)
if (foundSharedInstances.IsNotAnEqualObjectTo(default(KeyValuePair<object, List<object>>)))
{
// Add our bound object to the list... maybe make sure it's not there already..
// Also ensure that we are not trying to bind the foundSharedInstances.Key --
// that is the instance being returned, so cannot act as its own parent.
// This is a critical error, so wil throw rather than return a value.
var illegalBoundParent = ReferenceEquals(boundParent, foundSharedInstances.Key);
if (illegalBoundParent)
{
ThrowArgumentException(nameof(Resolve), "A returned instance cannot be bound to itself.");
return null;
}
// If the bound parent is already there, do not re-add it.
var parentIsAlreadyStored = foundSharedInstances.Value.Any(existingBoundParent =>
ReferenceEquals(existingBoundParent,
boundParent));
if (!parentIsAlreadyStored)
{
// ReSharper disable once AssignNullToNotNullAttribute
_sharedInstancesWithBoundMembers[foundSharedInstances.Key].Add(boundParent);
}
// Return the key object, as that is the one that is being shared between the list of bound instances
return foundSharedInstances.Key;
}
}
// ELSE must instantiate
// Try the creator
object instantiatedObject = null;
if (ProvidedCreatorFailed(resolutionToSeek, finalTypeRequestedT, ref instantiatedObject))
{
ThrowArgumentException(nameof(Resolve),
"Provided constructor did not create the expected type ->" + finalTypeRequestedT +
"<-");
return null;
}
if (CouldNotCreateObject(qualifyingMasterType, ref instantiatedObject))
{
ThrowOperationException(nameof(Resolve),
"Could not construct an object for base type ->" + qualifyingMasterType + "<-");
return null;
}
// The last step is to determine if we have to save the new object in our container.
// If global, yes -- this will only occur once
switch (ruleRequested)
{
case StorageRules.GlobalSingleton:
CreateSingletonInstance(instantiatedObject, finalTypeRequestedT);
break;
case StorageRules.SharedDependencyBetweenInstances:
CreateSharedInstances(instantiatedObject, finalTypeRequestedT, boundParent);
break;
}
return instantiatedObject;
}
/// <summary>
/// Removes a list of types that the parent type can be resolved as. Includes creators and storage rules.
/// </summary>
/// <typeparam name="TParent">The generic parent type</typeparam>
/// <param name="typesToUnregister">The types to remove.</param>
public void UnregisterTypeContracts<TParent>(params Type[] typesToUnregister)
{
if (!_registeredTypeContracts.ContainsKey(typeof(TParent)))
{
ThrowArgumentException(nameof(UnregisterTypeContracts),
"The type ->" + typeof(TParent) +
"<- cannot be unregistered because it was never is not registered");
return;
}
// If no sub types named, try to clear the main type, which kills all sub elements
if (typesToUnregister.IsEmpty())
{
_registeredTypeContracts.Remove(typeof(TParent));
return;
}
// ELSE remove the sub types individually
var parentRegistrations = _registeredTypeContracts[typeof(TParent)];
foreach (var type in typesToUnregister)
{
if (parentRegistrations.CreatorsAndStorageRules.ContainsKey(type))
{
parentRegistrations.CreatorsAndStorageRules.Remove(type);
}
}
// If this leaves the collection empty, remove it.
if (parentRegistrations.CreatorsAndStorageRules.IsEmpty())
{
_registeredTypeContracts.Remove(typeof(TParent));
}
}
/// <summary>
/// Clears the exceptions.
/// </summary>
protected void ClearExceptions()
{
IsArgumentExceptionThrown = string.Empty;
IsOperationExceptionThrown = string.Empty;
}
/// <summary>
/// Adds a list of bound instances to a single shared instance.
/// </summary>
/// <param name="sharedInstance">The shared instance.</param>
/// <param name="sharedInstanceType">
/// The type of the object. The shared instance is often just an object without a final
/// type.
/// </param>
/// <param name="boundParents">The bound member. Each of these are a different "parent" to the same shared instance.</param>
protected void CreateSharedInstances
(
object sharedInstance,
Type sharedInstanceType,
params object[] boundParents
)
{
if (!_sharedInstancesWithBoundMembers.ContainsKey(sharedInstance))
{
_sharedInstancesWithBoundMembers.Add(sharedInstance, new List<object>(boundParents));
}
else
{
var boundInstances = _sharedInstancesWithBoundMembers[sharedInstance];
foreach (var parent in boundParents)
{
if (boundInstances.All(bi => !ReferenceEquals(bi, parent)))
{
boundInstances.Add(parent);
}
}
}
}
/// <summary>
/// Adds a key-value pair with a class type and an instance of that class.
/// </summary>
/// <param name="instance">The instance of the type.</param>
/// <param name="typeToSaveAs">The keyed type for storage.</param>
protected void CreateSingletonInstance
(
object instance,
Type typeToSaveAs
)
{
if (!_globalSingletonsByType.ContainsKey(typeToSaveAs))
{
_globalSingletonsByType.Add(typeToSaveAs, instance);
}
else
{
_globalSingletonsByType[typeToSaveAs] = instance;
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only
/// unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
ReleaseUnmanagedResources();
if (disposing)
{
}
}
/// <summary>
/// Releases the unmanaged resources.
/// </summary>
protected virtual void ReleaseUnmanagedResources()
{
ResetContainer();
}
/// <summary>
/// Removes a bound instance from all shared instances. Also cleans up any orphaned shared instances.
/// </summary>
/// <param name="obj">The object.</param>
protected void RemoveBoundSharedDependencies(object obj)
{
if (_sharedInstancesWithBoundMembers.IsEmpty())
{
return;
}
var sharedInstancesIndexesToDelete = new List<int>();
for (var sharedInstanceIdx = 0;
sharedInstanceIdx < _sharedInstancesWithBoundMembers.Count;
sharedInstanceIdx++)
{
var keyToSeek = _sharedInstancesWithBoundMembers.Keys.ToList()[sharedInstanceIdx];
var sharedInstance = _sharedInstancesWithBoundMembers[keyToSeek];
var foundBoundMembers = sharedInstance.Where(si => ReferenceEquals(si, obj)).ToArray();
if (!foundBoundMembers.Any())
{
continue;
}
foreach (var foundBoundMember in foundBoundMembers)
{
sharedInstance.Remove(foundBoundMember);
}
// If the shared instance is empty, it must be removed, but best to do so after this iteration.
if (sharedInstance.IsEmpty())
{
sharedInstancesIndexesToDelete.Add(sharedInstanceIdx);
}
}
// Remove the shared instances that are now orphaned
foreach (var sharedInstanceIdx in sharedInstancesIndexesToDelete.ToArray())
{
// This has been revised, so will fail on removal
var keyToSeek = _sharedInstancesWithBoundMembers.Keys.ToList()[sharedInstanceIdx];
_sharedInstancesWithBoundMembers.Remove(keyToSeek);
}
}