Search code examples
delphidependency-injectionspring4d

How inject object to class not registered in container?


I have three classes. Class TA uses TB, Class TB uses TC.

In container I have registered TA and TC, TB is not required to be registered.

procedure Project;
var
    a: TA;
begin
    GlobalContainer.RegisterType<TA>.AsSingleton;
    GlobalContainer.RegisterType<TC>.AsSingleton;

    GlobalContainer.Build;
    a := GlobalContainer.Resolve<TA>;
end;

classes definitions:

TA = class
private
    _b: TB;
public
    constructor Create;
end;

TB = class
private
    _c: TC;
public
    procedure SetC(c: TC);
end;

TC = class
public
    data: String;
end;

constructor TA.Create;
begin
    _b := TB.Create;
end;

procedure TB.SetC(c: TC);
begin
    _c  := c;
end;

What should I do if I want inject TC instance to TB instance, when TB is not managed by container? Is it possible to do it without registration TB?


Solution

  • If TB is created inside of TA.Create then the container has no access to it unless you want to expose the instance in order to inject something into it but then again you are defeating the containers purpose which is to handle instance creation including their dependency graph.

    You have these dependencies (arrow means "needs dependency"): TA → TB → TC

    Now you have TA and TC known by the container but not TB not.

    Make TB injectable into TA, register it and when you resolve TA, it will build the complete object graph.