Validation of dependency injection container build

224 Views Asked by At

When I build application using dependency injection container(Spring4D) I would like to know if container is build up correctly. In this situation:

GlobalContainer.RegisterType<TApp>;
GlobalContainer.RegisterType<TMyForm>;
GlobalContainer.Build;

If TMyForm inherits from Vcl.Forms.TForm then container will built up but application won't work because in fact TMyForm is not registered at all. I would like to know if there is any possibility to validate build process. Especially will resolver resolve the constructor that I think it should, not the default one?

I tried something like that:

var
    registeredTypes: Spring.Collections.IEnumerable<TComponentModel>;
    registeredType: TComponentModel;
begin
    GlobalContainer.RegisterType<TApp>;
    GlobalContainer.RegisterType<TMyForm>;
    GlobalContainer.Build;

    registeredTypes := GlobalContainer.Kernel.Registry.FindAll;
    for registeredType in registeredTypes do
    begin
         if not GlobalContainer.Kernel.Registry.HasService(registeredType.ComponentTypeInfo) then
            raise Exception.Create('Build Error');
    end;

But this is far from ideal.

1

There are 1 best solutions below

0
On

After night searches and tests I am able to achieve what I intended. If you just register type like that:

GlobalContainer.RegisterType<TApp>;

container will resolve this type using 1st contructor which he is able to use. To force container to use exaclly this constructor what you want, you have to mark this constructor [Injected], like that:

TApp = class
private
    _form: TMyForm;
    _a: TAppCos;
public
    constructor Create; overload;
    constructor Create(form: TMyForm); overload;
    [Inject]
    constructor Create(a: TAppCos); overload;
end;
...
GlobalContainer.RegisterType<TApp>;

Now container will try resolve constructor Create(a: TAppCos) and if it's fail he will show a message like: "Can not resolve: TApp".(Not use another as before). And this is what I wanted to achive.

Edited: Don't forget about add Spring.Container.Common to uses in TApp unit.