我正在努力使用Spring4D的构造函数注入.在某个类中,我想将一个接口的特定实现(按名称)注入构造函数中.
看这个:
IListFactory = interface
['{40...29}']
function GetList : IListOfSomething;
end;
ICiderPress = interface
['{50...10}']
procedure Press;
end;
TAppleListFactory = class(TInterfacedObject, IListFactory)
function GetList : IListOfSomething;
end;
TCiderPress = class(TInterfacedObject, ICiderPress)
private
FListFactory : IListFactory;
public
constructor Create(const ListFactory : IListFactory);
procedure Press;
end;
implementation
function TCiderPress.Create(const ListFactory : IListFactory);
begin
FListFactory := ListFactory;
end;
procedure TCiderPress.Press;
begin
// Do somtihing with FListFactory
end;
initialization
GlobalContainer.RegisterType<TAppleListFactory>.Implements<IListFactory>('apple');
GlobalContainer.RegisterType<TCiderPress>.Implements<ICiderPress>;
end.
Run Code Online (Sandbox Code Playgroud)
现在我使用ServiceLocator获取我的印刷机实例:
CiderPress := ServiceLocator.GetService<ICiderPress>;
CiderPress.Press;
Run Code Online (Sandbox Code Playgroud)
它工作正常.
现在我添加第二个ListFactory:
TOrangeListFactory = class(TInterfacedObject, IListFactory)
function …Run Code Online (Sandbox Code Playgroud)