Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most minimal way to achieve Dependency Injection?

I've been reading about Spring and although it's claimed to be a less complex alternative to EJB, I'm having a hard time wrapping my head around it. Is there a more minimal way of achieving Dependency Injection than adopting the Spring approach?

like image 424
Chuck Avatar asked Mar 26 '10 21:03

Chuck


2 Answers

Why not just do it without a framework ?

Ask what your class depends on, and then inject those objects via (say) the constructor.

Some hints:

  1. does your class rely on a singleton ? Inject that object instead (probably as a factory)
  2. does your object rely on other concrete classes ? If so, inject those, but reference them via interfaces, so you can substitute different implementations

e.g. simply create a class with a constructor thus:

public TradeSaver(final ITradeValidator validator, final ITradeDatabase db);

(where both parameters are interfaces) and you can then inject the core components that your TradeSaver depends on (validation and database saving), with the option of providing different implementations for testing, different deployments etc.

like image 153
Brian Agnew Avatar answered Oct 12 '22 23:10

Brian Agnew


Google Guice is a very minimalist DI framework.

like image 31
Michael Borgwardt Avatar answered Oct 12 '22 22:10

Michael Borgwardt