-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxLogic.DI.Bootstrap.pas
More file actions
964 lines (804 loc) · 29 KB
/
Copy pathMaxLogic.DI.Bootstrap.pas
File metadata and controls
964 lines (804 loc) · 29 KB
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
unit MaxLogic.DI.Bootstrap;
{$REGION 'docu'}
(**
This unit provides a reusable foundation for setting up a Dependency Injection Composition Root using Spring4D.
Key Components:
- TDependencyRegistry: A singleton that acts as a central, application-wide
"shopping list" of required interface dependencies. It is designed to
ensure application stability, especially in hybrid legacy projects.
- TDICompositionRoot: A base class that orchestrates the registration
and validation of dependencies using the Container.
How to use this:
1. In your project-specific unit (e.g., Toggl.AppRoot), create a class
that inherits from TDICompositionRoot.
2. In the `initialization` section of any unit that has a dependency,
register that dependency's interface type with the TDependencyRegistry.
Example:
`TDependencyRegistry.Instance.RegisterRequirement(TypeInfo(IMyService), TSomeUnit.UnitName);`
or
`TDependencyRegistry.Instance.RegisterRequirementsFrom(TMyClass);
3. In your application's startup code (.dpr), create your AppRoot and call
its SetUp method before running the main form. SetUp will:
- call BeforeRegisterDependencies
- register all modules
- build the container
- optionally ValidateDependencies
- call AfterRegisterDependencies
1. **Ultimate Safety in Hybrid/Legacy Systems:** This is its killer feature. In a large, old application, you cannot possibly put every single class into the DI container. You will have old, legacy classes that are created manually (`TMyLegacyClass.Create`). If such a class needs an `ILogger`, it can't get it from a constructor. It will likely ask a global service locator for it. The `TDependencyRegistry` allows this legacy class to still participate in the startup validation. In its unit's `initialization` section, it declares, "Hey, I exist, and I'm going to need an `ILogger`!" The registry adds `ILogger` to the master list, ensuring that even this legacy component's needs are verified at startup.
2. **Decouples the "Need" from the "Implementation":** A unit containing a service interface and its consumer doesn't need to know *anything* about the concrete implementation. It only needs to know about the `TDependencyRegistry`. It declares its need, and it's up to a completely different part of the application (the `AppRoot`) to provide the implementation. This maintains excellent separation of concerns.
3. **Prevents Runtime "Time Bombs":** The alternative is discovering a missing dependency at runtime, often triggered by a specific user action (like clicking a button that opens a new form). This is the worst possible time for an application to fail. The registry moves this failure from a random point at runtime to a predictable, guaranteed point at startup, where a developer can immediately see it and fix it.
4. **Serves as Living Documentation:** A developer can look at the `ValidateDependencies` method and, by extension, the contents of the registry at runtime, to get a perfect, up-to-date list of all the core services the application is built upon. It's a self-documenting map of the application's architecture.
The `TDependencyRegistry` pattern is most valuable and shines brightest in these scenarios:
* **Gradual Refactoring of Legacy Applications:** This is the #1 use case. When you are slowly introducing DI into a large, existing codebase, this pattern is your safety net. It allows new and old code to coexist safely.
* **Large, Modular Applications:** In systems with many modules or plugins, where each module can have its own dependencies, the registry allows each module to independently declare its needs without creating tight coupling between them. The main application shell can then validate that all requirements from all loaded modules are met.
* **High-Reliability Systems:** In applications where runtime failures are unacceptable, this startup validation provides a critical layer of defense against configuration errors.
* **Teams with Varying Skill Levels:** It creates a simple, easy-to-follow pattern ("If your class needs a service, add it to the registry in the `initialization` section"). This reduces the mental overhead for developers and makes it less likely they will forget a crucial step.
Remark:
if spring4D does not call your constructors , ensure your have the following declared:
{$RTTI INHERIT
METHODS([vcPublic, vcPublished])
PROPERTIES([vcPublic, vcPublished])
FIELDS([vcPrivate, vcProtected, vcPublic, vcPublished])
}
or use: `{$I maxlogic.RttiEx.inc}`
There is also a helper script to find pas files that use BuildUp but do not have this inc file - see: find-missing-rttiEx.inc-when-using-BuildUp.ps1
**)
{$ENDREGION 'docu'}
interface
uses
System.SysUtils, System.Classes, System.Rtti, System.generics.collections, System.TypInfo,
Spring, Spring.Container, Spring.Container.Common, Spring.Services;
type
TValidationMode = (vmRegisteredOnly, vmResolveAtStartup, vmIgnore);
{ Put this on ctor parameters, fields, or properties
Usage:
constructor TSomeService.Create(
[DIRequire] Logger: ILogger; // just must be registered
[DIRequire(vmResolveAtStartup)] Repo: IUserRepository; // must be resolvable at startup
const TenantId: Integer // runtime param => NOT annotated
);
}
DIRequireAttribute = class(TCustomAttribute)
public
Mode: TValidationMode;
constructor Create(aMode: TValidationMode = vmRegisteredOnly);
end;
// Forward declaration
TDependencyRegistry = class;
TDICompositionRoot = class;
/// <summary>
/// Stores a dependency requirement plus the known requesters.
/// </summary>
TDependencyRequirement = class
private
fMode: TValidationMode;
fRequesters: TStringList;
public
constructor Create(aMode: TValidationMode);
destructor Destroy; override;
procedure AddRequester(const aUnitName, aClassName: string);
property Mode: TValidationMode read fMode write fMode;
property Requesters: TStringList read fRequesters;
end;
/// <summary>
/// A singleton registry to collect all required dependency types from across the application.
/// Its primary purpose is to enable robust, fail-fast validation at application startup.
/// </summary>
TDependencyRegistry = class
private
fRequired: TObjectDictionary<PTypeInfo, TDependencyRequirement>;
fDirty: Boolean;
class var fInstance: TDependencyRegistry;
constructor Create;
class destructor DestroyClass;
// Core scanner that works purely on TRttiType (no instance required)
procedure RegisterRequirementsFromRttiType(const aRttiType: TRttiType; const aRequesterUnit, aRequesterClass: string);
public
destructor Destroy; override;
/// <summary>
/// Provides access to the single instance of the registry.
/// </summary>
class function Instance: TDependencyRegistry;
/// <summary>
/// Declares that the application has a requirement for a service implementing
/// the interface specified by aTypeInfo. This should be called from the
/// `initialization` section of units that contain classes with dependencies.
/// </summary>
procedure RegisterRequirement(aTypeInfo: PTypeInfo; const aUnitName: string; aMode: TValidationMode = vmRegisteredOnly); overload;
procedure RegisterRequirement(aTypeInfo: PTypeInfo; const aUnitName, aClassName: string; aMode: TValidationMode = vmRegisteredOnly); overload;
procedure RegisterRequirement<T>(const aUnitName: string; aMode: TValidationMode = vmRegisteredOnly); overload;
procedure RegisterRequirement<T>(const aUnitName, aClassName: string; aMode: TValidationMode = vmRegisteredOnly); overload;
/// <summary>
/// Scans the given class type for [Inject]-and/or [DIRequire] decorated fields and properties
/// and registers their service types as requirements.
/// </summary>
procedure RegisterRequirementsFrom(aClass: TClass); overload;
/// Generic convenience overload that scans type T for [Inject] and [DIRequire]fields
procedure RegisterRequirementsFrom<T: class>; overload;
/// <summary>
/// Returns an array of all unique interface types that have been registered
/// as requirements for the application.
/// </summary>
function GetRequiredTypes: TArray<PTypeInfo>;
function GetMode(aTypeInfo: PTypeInfo): TValidationMode;
function GetRequestersText(aTypeInfo: PTypeInfo): string;
/// <summary>
/// Returns the list of required service types as a JSON array of strings.
/// Useful for generating "live architecture" docs."
/// </summary>
function DumpRequiredTypesToJson: string;
/// <summary>
/// Invokes a callback for each required type with its qualified name.
/// Use this to log or display the dependency manifest.
/// </summary>
procedure LogRequiredTypes(const aLogger: TProc<string>);
end;
TDIRegistrationModule = class
public
procedure BeforeRegisterDependencies(aRoot: TDICompositionRoot); virtual;
// Centralized method for registering all application dependencies.
procedure RegisterDependencies(aContainer: TContainer); virtual;
// called after RegisterDependencies + fContainer.Build
procedure AfterRegisterDependencies(aRoot: TDICompositionRoot); virtual;
end;
/// <summary>
/// A base class that provides the core logic for a Composition Root.
/// It orchestrates the registration and validation of dependencies.
/// </summary>
TDICompositionRoot = class
private Type
TRegistrationEntry = record
private
fModule: TDIRegistrationModule; // owned by root
fProc: TProc<TContainer>; // external procedure-based registration
end;
private
fRegistrationEntries: TList<TRegistrationEntry>;
protected
fContainer: TContainer;
procedure BeforeRegisterDependencies; virtual;
// Centralized method for registering all application dependencies.
procedure RegisterDependencies; virtual;
// called after RegisterDependencies + fContainer.Build
procedure AfterRegisterDependencies; virtual;
// Force a fast-fail if a required dependency cannot be resolved.
procedure ValidateDependencies; virtual;
public
// NOTE: if aContainer = nil, then the global container will be used
constructor Create(aContainer: TContainer = nil);
destructor destroy; override;
// Centralized method for registering all application dependencies.
procedure SetUp(aValidate: Boolean = True); virtual;
// those methods will be invoked in the `RegisterDependencies` method
procedure AddModule(aProc: TProc<TContainer>); overload;
procedure AddModule(const aProcArray: TArray<TProc<TContainer>>); overload;
// Registers a class-based DI module. The composition root takes ownership of aModule and will free it in its destructor.
procedure AddModule(aModule: TDIRegistrationModule); overload;
procedure AddModule(const aModules: TArray<TDIRegistrationModule>); overload;
property Container: TContainer read fContainer;
end;
TContainerHelper = class helper for TContainer
// lField/property injection for legacy objects that are not created by the container.
procedure BuildUp(const AInstance: TObject; aOverwriteExisting: Boolean = false);
function HasService<T>: Boolean; overload;
function HasService(aTypeInfo: PTypeInfo): Boolean; overload;
end;
implementation
{ helper methods }
function GetValidationMode(const aAttributes: TArray<TCustomAttribute>; out aReq: DIRequireAttribute): TValidationMode;
begin
aReq:= nil;
Result:= vmRegisteredOnly;
for var attr in aAttributes do
if attr is DIRequireAttribute then
begin
aReq := DIRequireAttribute(attr);
Result:= aReq.Mode;
Break;
end;
end;
function GetInject(const aAttributes: TArray<TCustomAttribute>; out aInject: InjectAttribute): Boolean;
begin
Result:= False;
aInject:= nil;
for var lAttr in aAttributes do
if lAttr is InjectAttribute then
begin
aInject:= InjectAttribute(lAttr);
Exit(True);
end;
end;
function ServiceTypeFromAttrOrMember(const aAttr: InjectAttribute; const aMemberType: TRttiType): PTypeInfo;
begin
Result := nil;
if Assigned(aAttr) then
Result := aAttr.ServiceType; // may be nil
if (Result = nil) and Assigned(aMemberType) then
Result := aMemberType.Handle;
end;
{ TDependencyRequirement }
constructor TDependencyRequirement.Create(aMode: TValidationMode);
begin
inherited Create;
fMode := aMode;
fRequesters := TStringList.Create;
fRequesters.Sorted := True;
fRequesters.Duplicates := dupIgnore;
end;
destructor TDependencyRequirement.Destroy;
begin
fRequesters.Free;
inherited;
end;
procedure TDependencyRequirement.AddRequester(const aUnitName, aClassName: string);
var
lUnitName: string;
lKey: string;
begin
lUnitName := aUnitName;
if lUnitName = '' then
lUnitName := '<unknown>';
if aClassName <> '' then
lKey := lUnitName + '.' + aClassName
else
lKey := lUnitName;
fRequesters.Add(lKey);
end;
{$IFDEF DEBUG}
var fPrevInitProc : Procedure;
procedure ValidateRegisteredDependencies;
begin
if TDependencyRegistry.Instance.fDirty then
raise Exception.Create(TDependencyRegistry.UnitName + ': You have untested dependencies registered with '+TDependencyRegistry.className);
if Assigned(fPrevInitProc) then
fPrevInitProc ();
end;
{$ENDIF}
{ TDependencyRegistry }
class function TDependencyRegistry.Instance: TDependencyRegistry;
begin
if not assigned(fInstance) then
fInstance := TDependencyRegistry.Create;
Result := fInstance;
end;
constructor TDependencyRegistry.Create;
begin
inherited Create;
fRequired:= TObjectDictionary<PTypeInfo, TDependencyRequirement>.Create([TDictionaryOwnership.doOwnsValues]);
end;
destructor TDependencyRegistry.Destroy;
begin
fRequired.Free;
inherited;
end;
class destructor TDependencyRegistry.DestroyClass;
begin
FreeAndNil(fInstance);
end;
procedure TDependencyRegistry.RegisterRequirement<T>(const aUnitName: string; aMode: TValidationMode);
begin
RegisterRequirement(TypeInfo(T), aUnitName, aMode);
end;
procedure TDependencyRegistry.RegisterRequirement<T>(const aUnitName, aClassName: string; aMode: TValidationMode);
begin
RegisterRequirement(TypeInfo(T), aUnitName, aClassName, aMode);
end;
procedure TDependencyRegistry.RegisterRequirement(aTypeInfo: PTypeInfo; const aUnitName: string; aMode: TValidationMode);
begin
RegisterRequirement(aTypeInfo, aUnitName, '', aMode);
end;
procedure TDependencyRegistry.RegisterRequirement(aTypeInfo: PTypeInfo; const aUnitName, aClassName: string; aMode: TValidationMode);
var
lExisting: TDependencyRequirement;
begin
if not Assigned(aTypeInfo) then
Exit;
if aMode = vmIgnore then
Exit;
fDirty := True;
if fRequired.TryGetValue(aTypeInfo, lExisting) then
begin
// "ResolveAtStartup" wins
if Ord(aMode) > Ord(lExisting.Mode) then
lExisting.Mode := aMode;
end else
begin
lExisting := TDependencyRequirement.Create(aMode);
fRequired.Add(aTypeInfo, lExisting);
end;
lExisting.AddRequester(aUnitName, aClassName);
end;
procedure TDependencyRegistry.RegisterRequirementsFromRttiType(const aRttiType: TRttiType; const aRequesterUnit, aRequesterClass: string);
var
lField: TRttiField;
lProp: TRttiProperty;
lAttr: TCustomAttribute;
lInject: InjectAttribute;
lServiceType: PTypeInfo;
var
m: TRttiMethod;
p: TRttiParameter;
lReq: DIRequireAttribute;
lMode: TValidationMode;
begin
if aRttiType = nil then
Exit;
// Fields with [Inject]
for lField in aRttiType.GetFields do
begin
lMode:= GetValidationMode(lField.GetAttributes , lReq);
lInject:= nil;
if lMode<> vmIgnore then
if Assigned(lReq) or GetInject(lField.GetAttributes , lInject) then
begin
lServiceType := ServiceTypeFromAttrOrMember(lInject, lField.FieldType);
RegisterRequirement(lServiceType, aRequesterUnit, aRequesterClass, lMode);
end;
end;
// Writable properties with [Inject]
for lProp in aRttiType.GetProperties do
begin
if not (lProp.IsWritable) then
Continue;
lMode:= GetValidationMode(lProp.GetAttributes , lReq);
lInject := nil;
if lMode <> vmIgnore then
if Assigned(lReq) or GetInject(lProp.GetAttributes , lInject) then
begin
lServiceType := ServiceTypeFromAttrOrMember(lInject, lProp.PropertyType);
RegisterRequirement(lServiceType, aRequesterUnit, aRequesterClass, lMode);
end;
end;
// Constructors
for m in aRttiType.GetMethods do
if m.IsConstructor and (m.Visibility = mvPublic) then
if Length(m.GetParameters) > 0 then
begin
for p in m.GetParameters do
begin
if GetValidationMode(p.GetAttributes , lReq) <> vmIgnore then
if Assigned(lReq) then
RegisterRequirement(p.ParamType.Handle, aRequesterUnit, aRequesterClass, lReq.Mode);
end;
end;
end;
procedure TDependencyRegistry.RegisterRequirementsFrom(aClass: TClass);
var
lCtx: TRttiContext;
lType: TRttiType;
begin
if not Assigned(aClass) then
Exit;
lCtx := TRttiContext.Create;
try
lType := lCtx.GetType(aClass); // RTTI by class ref, no instance needed
RegisterRequirementsFromRttiType(lType, aClass.UnitName, aClass.ClassName);
finally
lCtx.Free;
end;
end;
procedure TDependencyRegistry.RegisterRequirementsFrom<T>;
var
lCtx: TRttiContext;
lType: TRttiType;
lClass: TClass;
begin
lCtx := TRttiContext.Create;
try
lType := lCtx.GetType(TypeInfo(T));
lClass := nil;
if lType is TRttiInstanceType then
lClass := TRttiInstanceType(lType).MetaclassType;
if Assigned(lClass) then
RegisterRequirementsFromRttiType(lType, lClass.UnitName, lClass.ClassName)
else
RegisterRequirementsFromRttiType(lType, '<unknown>', lType.Name);
finally
lCtx.Free;
end;
end;
function TDependencyRegistry.GetMode(aTypeInfo: PTypeInfo): TValidationMode;
var
lReq: TDependencyRequirement;
begin
if fRequired.TryGetValue(aTypeInfo, lReq) then
Result := lReq.Mode
else
Result:= TValidationMode.vmRegisteredOnly; // default
end;
function TDependencyRegistry.GetRequiredTypes: TArray<PTypeInfo>;
begin
Result := fRequired.Keys.ToArray;
end;
function TDependencyRegistry.GetRequestersText(aTypeInfo: PTypeInfo): string;
var
lReq: TDependencyRequirement;
i: Integer;
begin
Result := '';
if not fRequired.TryGetValue(aTypeInfo, lReq) then
Exit;
if lReq.Requesters.Count = 0 then
Exit;
for i := 0 to lReq.Requesters.Count - 1 do
begin
if Result <> '' then
Result := Result + '; ';
Result := Result + lReq.Requesters[i];
end;
end;
function TDependencyRegistry.DumpRequiredTypesToJson: String;
var
lTypes: TArray<PTypeInfo>;
lCtx: TRttiContext;
lFirst: Boolean;
lTypeInfo: PTypeInfo;
lTypeName: string;
lJson: string;
function JsonEscape(const aValue: string): string;
var
lCh: Char;
begin
Result := '';
for lCh in aValue do
begin
case lCh of
'"': Result := Result + '\"';
'\': Result := Result + '\\';
#8: Result := Result + '\b';
#9: Result := Result + '\t';
#10: Result := Result + '\n';
#12: Result := Result + '\f';
#13: Result := Result + '\r';
else
// Keep it simple: assume everything else is fine as-is
Result := Result + lCh;
end;
end;
end;
begin
Result:= '';
lTypes := GetRequiredTypes;
lCtx := TRttiContext.Create;
try
// Start JSON array
lJson := '[';
lFirst := True;
for lTypeInfo in lTypes do
begin
if not Assigned(lTypeInfo) then
begin
Continue;
end;
lTypeName := lCtx.GetType(lTypeInfo).QualifiedName;
if not lFirst then
lJson := lJson + ',';
lFirst := False;
lJson := lJson + '"' + JsonEscape(lTypeName) + '"';
end;
lJson := lJson + ']';
Result:= lJson;
finally
lCtx.Free;
end;
end;
procedure TDependencyRegistry.LogRequiredTypes(const aLogger: TProc<string>);
var
lTypes: TArray<PTypeInfo>;
lCtx: TRttiContext;
lTypeInfo: PTypeInfo;
lTypeName: string;
begin
if not Assigned(aLogger) then
begin
Exit;
end;
lTypes := GetRequiredTypes;
lCtx := TRttiContext.Create;
try
for lTypeInfo in lTypes do
begin
if not Assigned(lTypeInfo) then
begin
Continue;
end;
lTypeName := lCtx.GetType(lTypeInfo).QualifiedName;
aLogger(lTypeName);
end;
finally
lCtx.Free;
end;
end;
{ TDICompositionRoot }
procedure TDICompositionRoot.AfterRegisterDependencies;
var
lIndex: Integer;
begin
// loop over a list that might grow during the iteration
lIndex:= 0;
while lIndex < fRegistrationEntries.Count do
begin
if fRegistrationEntries[lIndex].fModule <> nil then
fRegistrationEntries[lIndex].fModule.AfterRegisterDependencies(self);
inc(lIndex);
end;
end;
procedure TDICompositionRoot.BeforeRegisterDependencies;
var
lIndex: Integer;
begin
// loop over a list that might grow during the iteration
lIndex:= 0;
while lIndex < fRegistrationEntries.Count do
begin
if fRegistrationEntries[lIndex].fModule <> nil then
fRegistrationEntries[lIndex].fModule.BeforeRegisterDependencies(self);
inc(lIndex);
end;
end;
procedure TDICompositionRoot.AddModule(aProc: TProc<TContainer>);
var
lModule: TRegistrationEntry;
begin
if not Assigned(aProc) then
Exit;
lModule.fModule := nil;
lModule.fProc := aProc;
fRegistrationEntries.Add(lModule);
end;
procedure TDICompositionRoot.AddModule(const aProcArray: TArray<TProc<TContainer>>);
begin
for var lProc in aProcArray do
AddModule(lProc);
end;
procedure TDICompositionRoot.AddModule(aModule: TDIRegistrationModule);
var
lModule: TRegistrationEntry;
begin
if not Assigned(aModule) then
Exit;
lModule.fModule := aModule;
lModule.fProc := nil;
fRegistrationEntries.Add(lModule);
end;
procedure TDICompositionRoot.AddModule(const aModules: TArray<TDIRegistrationModule>);
var
lMod: TDIRegistrationModule;
begin
for lMod in aModules do
AddModule(lMod);
end;
constructor TDICompositionRoot.Create(aContainer: TContainer);
begin
inherited Create;
if aContainer = nil then
fContainer := GlobalContainer
else
fContainer := aContainer;
fRegistrationEntries:= TList<TRegistrationEntry>.Create;
end;
destructor TDICompositionRoot.destroy;
begin
for var x := 0 to fRegistrationEntries.Count-1 do
begin
if assigned(fRegistrationEntries[x].fModule) then
fRegistrationEntries[x].fModule.Free;
end;
fRegistrationEntries.Free;
inherited;
end;
procedure TDICompositionRoot.RegisterDependencies;
var
lIndex: Integer;
begin
// loop over a list that might grow during the iteration
lIndex:= 0;
while lIndex < fRegistrationEntries.Count do
begin
if fRegistrationEntries[lIndex].fModule <> nil then
fRegistrationEntries[lIndex].fModule.RegisterDependencies(fContainer)
else if Assigned(fRegistrationEntries[lIndex].fProc) then
fRegistrationEntries[lIndex].fProc(fContainer);
inc(lIndex);
end;
end;
procedure TDICompositionRoot.SetUp(aValidate: Boolean = True);
begin
BeforeRegisterDependencies;
RegisterDependencies;
fContainer.Build;
if aValidate then
begin
// Fail fast if anything is mis-registered or missing.
ValidateDependencies;
end;
AfterRegisterDependencies;
end;
procedure TDICompositionRoot.ValidateDependencies;
var
lRequiredType: PTypeInfo;
lTypeName: string;
lRequesterText: string;
lServiceLocator: IServiceLocator;
lCtx: TRttiContext;
begin
if not TDependencyRegistry.Instance.fDirty then
Exit;
TDependencyRegistry.Instance.fDirty:= False;
lServiceLocator := TServiceLocatorAdapter.Create(fContainer);
lCtx := TRttiContext.Create;
try
for lRequiredType in TDependencyRegistry.Instance.GetRequiredTypes do
begin
lTypeName := lCtx.GetType(lRequiredType).QualifiedName;
lRequesterText := TDependencyRegistry.Instance.GetRequestersText(lRequiredType);
if lRequesterText <> '' then
lRequesterText := sLineBreak + 'Required by: ' + lRequesterText;
// 1. Check if the interface is registered using the correct method.
if not lServiceLocator.HasService(lRequiredType) then
raise EContainerException.CreateFmt(
'Startup Validation Failed: The required service "%s" is declared as a dependency but is not registered in the DI container.%s',
[lTypeName, lRequesterText]
);
// 2. Try to actually resolve it.
if TDependencyRegistry.Instance.GetMode(lRequiredType) = vmResolveAtStartup then
try
fContainer.Resolve(lRequiredType);
except
on e: Exception do
raise EContainerException.CreateFmt(
'Startup Validation Failed: Could not resolve the required service "%s". Check its own dependencies. Original Error: %s%s',
[lTypeName, e.Message, lRequesterText]
);
end;
end;
finally
lCtx.Free;
end;
end;
{ TContainerHelper }
function TContainerHelper.HasService<T>: Boolean;
begin
Result:= HasService(TypeInfo(T));
end;
function TContainerHelper.HasService(aTypeInfo: PTypeInfo): Boolean;
var
lServiceLocator: IServiceLocator;
begin
lServiceLocator := TServiceLocatorAdapter.Create(self);
Result:= lServiceLocator.HasService(aTypeInfo);
end;
procedure TContainerHelper.BuildUp(const AInstance: TObject; aOverwriteExisting: Boolean = false);
var
Ctx: TRttiContext;
lCurType: TRttiType;
lField: TRttiField;
lProp: TRttiProperty;
function IsUnset(const V: TValue): Boolean;
begin
if V.IsEmpty then Exit(True);
if V.Kind = tkClass then Exit(V.AsObject = nil);
if V.Kind = tkInterface then Exit(V.AsInterface = nil);
Result := False;
end;
function IsInjectableType(aTypeInfo: PTypeInfo): Boolean;
begin
Result :=
Assigned(aTypeInfo) and
(aTypeInfo^.Kind in [tkInterface, tkClass]);
end;
function TryGetInjectionType(
const Attrs: TArray<TCustomAttribute>;
const MemberType: TRttiType;
out TypeInfoToResolve: PTypeInfo
): Boolean;
var
lReq: DIRequireAttribute;
lMode: TValidationMode;
lInject: InjectAttribute;
begin
TypeInfoToResolve := nil;
lMode := GetValidationMode(Attrs, lReq);
if lMode = vmIgnore then
Exit(False);
GetInject(Attrs, lInject);
// inject if DIRequire present OR Inject present
if (lReq = nil) and (lInject = nil) then
Exit(False);
TypeInfoToResolve := ServiceTypeFromAttrOrMember(lInject, MemberType);
Result := IsInjectableType(TypeInfoToResolve);
end;
procedure InjectFieldIfNeeded(const Obj: TObject; const F: TRttiField; const TI: PTypeInfo);
var
lCur: TValue;
begin
lCur := F.GetValue(Obj);
if aOverwriteExisting or IsUnset(lCur) then
F.SetValue(Obj, Self.Resolve(TI));
end;
procedure InjectPropIfNeeded(const Obj: TObject; const P: TRttiProperty; const TI: PTypeInfo);
var
lCur: TValue;
begin
if (not P.IsWritable) then
Exit;
lCur := P.GetValue(Obj);
if aOverwriteExisting or IsUnset(lCur) then
P.SetValue(Obj, Self.Resolve(TI));
end;
var
TI: PTypeInfo;
begin
if not Assigned(AInstance) then
Exit;
Ctx := TRttiContext.Create;
try
lCurType := Ctx.GetType(AInstance.ClassType);
// scan this class and all its BaseTypes. This makes BuildUp robust even if some derived class has strict RTTI settings.
while Assigned(lCurType) do
begin
// Fields
for lField in lCurType.GetFields do
begin
if not TryGetInjectionType(lField.GetAttributes, lField.FieldType, TI) then
Continue;
try
InjectFieldIfNeeded(AInstance, lField, TI);
except
on E: Exception do
raise EContainerException.CreateFmt(
'BuildUp failed for %s.%s (%s): %s',
[AInstance.ClassName, lField.Name, lField.FieldType.Name, E.Message]
);
end;
end;
// Properties
for lProp in lCurType.GetProperties do
begin
if (not lProp.IsWritable) then
Continue;
if not TryGetInjectionType(lProp.GetAttributes, lProp.PropertyType, TI) then
Continue;
try
InjectPropIfNeeded(AInstance, lProp, TI);
except
on E: Exception do
raise EContainerException.CreateFmt(
'BuildUp failed for %s.%s (%s): %s',
[AInstance.ClassName, lProp.Name, lProp.PropertyType.Name, E.Message]
);
end;
end;
lCurType := lCurType.BaseType;
end;
finally
Ctx.Free;
end;
end;
{ TDIRegistrationModule }
procedure TDIRegistrationModule.AfterRegisterDependencies(
aRoot: TDICompositionRoot);
begin
end;
procedure TDIRegistrationModule.BeforeRegisterDependencies(
aRoot: TDICompositionRoot);
begin
end;
procedure TDIRegistrationModule.RegisterDependencies(
aContainer: TContainer);
begin
end;
{ DIRequireAttribute }
constructor DIRequireAttribute.Create(aMode: TValidationMode);
begin
inherited Create;
Mode := aMode;
end;
initialization
{$IFDEF DEBUG}
// Deferred validation: called from Application.Initialize in DEBUG builds
// in case the dependencies are never explicitly validated during startup.
fPrevInitProc:= InitProc;
InitProc := @ValidateRegisteredDependencies;
{$ENDIF}
end.