Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Dependency Injection Manually Implemented?

How we can manually inject an object without using the facility of containers. I did something similar through reflection as follows.

Class actionClass = Class.forName("SampleClass");
Object actionObject = actionClass.newInstance();
Method reqMethod = actionClass.getMethod("setRequest", HttpServletRequest.class);
reqMethod.invoke(actionObject,request);

is it the right way to do DI?

My intention is to pass request object to different controller classes dynamically from a dispatcher filter,where we get request and response objects. I am fearing about the performace of reflection.Is there any replacement for doing DI?

like image 788
Biju CD Avatar asked Aug 21 '10 09:08

Biju CD


2 Answers

Dependency injection is nothing more than providing a class with its dependencies, rather than have it find them itself (via singletons/lookups etc.). So you can do it in code trivially thus:

DatabaseConnection dc = new DatabaseConnection();
MyDAO dao = new MyDAO(dc);

(pseudocode). Here the MyDAO is being injected with a database connection. If that database connection implements an interface you can easily mock this out during testing.

like image 97
Brian Agnew Avatar answered Nov 01 '22 22:11

Brian Agnew


Well, when you set one object into another object using setter method or through a constructor it also is the dependency injection. Dependency injection only means creating relationship(dependency) in objects.

Using reflection as you did is just another form of it.

like image 27
Gopi Avatar answered Nov 01 '22 23:11

Gopi