Spring4D Manual
DI, Collections, Mapping, Events for Delphi.
1. Dependency Injection
Register & Resolve
Container := TContainer.Create;
Container.RegisterType<IMyInterface, TMyImplementation>.AsSingleton;
MyInterface := Container.Resolve<IMyInterface>;
Lifetime
AsSingleton- Single shared instanceAsTransient- New instance each timeAsScoped- Scoped instance
Constructor Injection
TMyImpl = class(TInterfacedObject, IMyInterface)
constructor Create(Dep: IOtherInterface);
end;
Container.RegisterType<IMyInterface, TMyImpl>;
Container.RegisterType<IOtherInterface, TOtherImpl>;
2. Collections
Lists
List := TCollections.CreateList<Integer>;
List.Add(1);
List.Add(2);
Dictionaries
Dict := TCollections.CreateDictionary<Integer, string>;
Dict.Add(1, 'One');
Thread-Safe
SafeList := TCollections.CreateThreadSafeList<Integer>;
3. Functional
FilteredList := List.Where(function(V: Integer): Boolean
begin Result := V > 2; end);
Sum := List.Aggregate(0, function(A, B: Integer): Integer
begin Result := A + B; end);
4. Lazy Init
LazyValue := Lazy<Integer>.Create(
function: Integer begin Result := ExpensiveCalc; end);
5. Events
Event := TEvent<TNotifyEvent>.Create;
Event.Add(MyHandler);
Event.Invoke(Sender);
6. Patterns
// Singleton
Container.RegisterType<TMySingleton>.AsSingleton;
// Factory
Container.RegisterType<IMyInterface>(function: IMyInterface
begin Result := TMyImpl.Create; end);