Registriert seit: 12. Aug 2003
Ort: Soest
4.016 Beiträge
Delphi 10.1 Berlin Enterprise
|
AW: Custom Constructor /DI bei factory-basierter Objekterstellung
13. Feb 2018, 08:48
Hier mal ein kleines Beispiel:
Delphi-Quellcode:
program Simple_DI;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
SimpleContainer in 'SimpleContainer.pas';
type
IX = interface
['{E2D88E1C-AE7D-491A-B456-84B134749890}']
end;
IY = interface
['{3D1256AB-CDDE-49B2-94CF-E9FA82314206}']
end;
IZ = interface
['{4F51DE5D-B65B-4776-B25B-5B2868DC34AC}']
end;
TX = class(TInterfacedObject, IX)
private
fy: IY;
fz: IZ;
public
constructor Create(const y: IY; const z: IZ);
end;
TY = class(TInterfacedObject, IY)
constructor Create;
end;
TZ = class(TInterfacedObject, IZ)
constructor Create;
end;
{ TX }
constructor TX.Create(const y: IY; const z: IZ);
begin
Writeln('creating ', ClassName);
Writeln('injected ', (y as TObject).ClassName, ' for y');
Writeln('injected ', (z as TObject).ClassName, ' for z');
fy := y;
fz := z;
end;
{ TY }
constructor TY.Create;
begin
Writeln('creating ', ClassName);
end;
{ TZ }
constructor TZ.Create;
begin
Writeln('creating ', ClassName);
end;
var
container: TSimpleContainer;
x: IX;
begin
// showing the so called register, resole, release (RRR) pattern
// see http://blog.ploeh.dk/2010/09/29/TheRegisterResolveReleasepattern/
container := TSimpleContainer.Create;
try
// register
container.Add<IX, TX>;
container.Add<IY, TY>;
container.Add<IZ, TZ>;
// resolve
x := container.Get<IX>;
finally
// release
x := nil;
container.Free;
end;
end.
Geändert von Stevie (13. Feb 2018 um 08:50 Uhr)
|
|
Zitat
|