How to use Factory Class and attributes in Delphi Spring4D

175 Views Asked by At

How to use attributes correctly to create different implementations for the IDog interface in the IDogFactory interface? Is it possible to create different implementations for one interface using Factory interface?

type
  IDog = interface
    function GetName: string;
    procedure Test;
  end;

  IDogFactory = interface(IInvokable)
    [TTola]
    function CreateTola: IDog;
    [TRudy]
    function CreateRudy: IDog;
  end;

  IFamillyDog = interface
    function Dogs: IList<IDog>;
    function Count: Integer;
  end;

  TTola = class(TInterfacedObject, IDog)
  public
    constructor Create;
    function GetName: string;
    procedure Test;
  end;

  TRudy = class(TInterfacedObject, IDog)
  public
    constructor Create;
    function GetName: string;
    procedure Test;
  end;

  TFamillyDog = class(TInterfacedObject, IFamillyDog)
  private
    fDogs: IList<IDog>;

    function Dogs: IList<IDog>;
    function Count: Integer;
  public
    constructor Create(aFactory: IDogFactory);
  end;

Tree:
 
  C.RegisterType<IDog, TTola>('Tola');
  C.RegisterType<IDog, TRudy>('Rudy');
  C.RegisterType<IFamillyDog, TFamillyDog>;
  C.RegisterType<IDogFactory>.AsFactory;

I tried to run the example code changing the details, I always get the error:

No default found for type IDog

1

There are 1 best solutions below

0
Stefan Glienke On

What you are trying is not supported.

I assume you are after a feature like what Castle Windsor can do.
It looks like a nice feature and I will consider adding in the future.

For the time being you have to implement the factory yourself as an auto factory built by the container does not support this.