Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Dependency Injection Framework for Delphi with attribute-based injection?

I would love to be able to code in Delphi this way, simply annotating a field:

type
  TMyClass = class
  private
    [Inject]
    Factory: ISomeFactory;
    ...
  end;

or by attributing a setter

type
  TMyClass = class
  private
    FFactory: ISomeFactory;

    [Inject]
    procedure SetFactory(const AFactory: ISomeFactory);
    ...
  public
    property Factory: ISomeFactory read FFactory write SetFactory;
  end;

The background: I am moving old code to a service-oriented architecture and find that referencing the service layer always leads to constructs like

DataModule1.ServiceLayerInstance1.SubSystemN.InvokeSomething(Params, ...);

which could be much shorter like

type
  Form1 = class(TForm1)
  private
    [Inject]
    SubsystemN: ISubsystemN;
    ...
  end;
  ...
  SubsystemN.InvokeSomething(Params, ...);
like image 785
mjn Avatar asked May 25 '12 13:05

mjn


2 Answers

You can achieve this goal with the Emballo OpenSource project.

See the project on Google Code: http://code.google.com/p/emballo/wiki/WhyDependencyInjection

like image 33
jfoliveira Avatar answered Oct 11 '22 23:10

jfoliveira


Yes, there is. The Delphi Spring Framework

http://www.spring4d.com/

does precisely this. It has an [Inject] attribute.

One caveat -- to use it, you need to include the Spring unit in your code where the attribute is defined. Otherwise, the compiler will ignore the attribute.

like image 60
Nick Hodges Avatar answered Oct 11 '22 23:10

Nick Hodges