3

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.

ここで、ServiceLocator を使用して印刷機のインスタンスを取得します。

CiderPress := ServiceLocator.GetService<ICiderPress>;
CiderPress.Press;

そしてそれはうまくいきます。

次に、2 つ目の ListFactory を追加します。

TOrangeListFactory = class(TInterfacedObject, IListFactory)
    function GetList : IListOfSomething;
end;

登録を追加します

GlobalContainer.RegisterType<TOrangeListFactory>.Implements<IListFactory>('orange');

私のシードルプレスクラスをに変更します

TCiderPress = class(TInterfacedObject, ICiderPress)
private
    FListFactory : IListFactory;
public
    [Inject]
    constructor Create([Inject('apple')]const ListFactory : IListFactory);

    procedure Press;
end;

問題は、TCiderPress の ctor が呼び出されないことです。

追加すると

GlobalContainer.AddExtension<TActivatorContainerExtension>;

EActivatorException: Unsatisfied contructor on type: TCiderPress が発生します

何がうまくいかないのですか?

編集:

次のように構築を委任すると、機能します。

GlobalContainer.RegisterType<TCiderPress>.Implements<ICiderPress>
    .DelegateTo(function : TCiderPress
        begin
            Result := TCiderPress.Create(ServiceLocator.GetService<IListFactory>('apple');
        end
    );

EDIT2:

私は私のエラーを見つけました!インターフェイスのuses句にSpring.Container.Commonを含める必要がありました。

Delphi XE3 と Spring4D 1.1.3 を使用しています。

4

1 に答える 1