I try to do a service Locator in Delphi, base on Malcom code I'm trying to get the GUID from an Interface passed as var in a method.
My Container class look like that :
TContainer = class
strict private
FDico: TObjectDictionary<TGUID, IInterface>;
[...]
public
procedure Register<ServiceType: IInterface>(IntfInstance : ServiceType);
function Get<ServiceType: IInterface>: ServiceType;
end;
To register a class, I need to do :
TContainer.Instance.Register<IFlying>(TBird.Create);
And I get it by :
var
F: IFlying;
begin
F := TContainer.GetInstance.Get<IFlying>;
F.Fly;
end;
What I want to do is :
TContainer.Instance.Register<IFlying>(TBird); // instead of .Create
Here is the Register class :
procedure TContainer.Register<ServiceType>(IntfInstance: ServiceType);
var
Guid: TGuid;
begin
Guid := PTypeInfo(TypeInfo(ServiceType)).TypeData.Guid;
FDico.Add(Guid, IntfInstance);
end;
And the Get class :
function TContainer.Get<ServiceType>: ServiceType;
var
Guid: TGuid;
LInterface : IInterface;
LSpecificInterface : ServiceType;
begin
Result := nil;
Guid := PTypeInfo(TypeInfo(ServiceType)).TypeData.Guid;
if FDico.TryGetValue(Guid, LInterface) then
begin
if Supports(LInterface, Guid, LSpecificInterface) then
begin
Result := LSpecificInterface;
end
else
raise EIntfCastError.Create(Format('Service %s not supported', [PTypeInfo(TypeInfo(ServiceType)).Name]));
end
else
raise Exception.Create(Format('Service %s not registered', [PTypeInfo(TypeInfo(ServiceType)).Name]));
end;