Types of Dependency Injection
Tuesday, May 4th, 2010 - By Abhishek Rakshit
In continuation with my effort of trying to simplify Dependency Injection, I want to elaborate on the different types of injection. Dependency Injection is decoupling an application and service so that the application does not need to know anything about the service implementation. Dependency injection can be broadly classified in three categories: Constructor, Setter and Interface.
public class Account {
public User user;
public Account (User user) {
this.user = user;
}
}
Pico Container is a framework which prefers constructor injection. Constructor injection ensures that the application object is created with all its service dependencies satisfied. The constructor arguments clearly delineates the dependencies and makes the code easy to understand. Using constructor injection also relieves the developer to explicitly check for the validity of the created object i.e the constructor enforces that all the dependencies for the required object have been injected already. Another advantage of constructor injection is that immutable properties can be hidden by not providing a setter. If setters are used to initialize these objects it can become a problem because not having a setter clearly signifies that the object is non modifiable. The code snippet shown above is a simple example of an Account class where the dependency of User class is injected through the constructor.
public class Account {
public User user;
public setUser (User user) {
this.user = user;
}
}
The third category is of Interface Injection where an interface defines the injection method. The method providing the implementation has to implement the interface and as such the service is dependent on the interface and not on the implementation. The example below shows the Account class which depends on the IUser interface and the AccountController class injects the required dependency in this case the object of the User class which implements the IUser interface.
public class Account {
public IUser user;
public setUser (IUser user) {
this.user = user;
}
}
public class AccountController {
public void initDefaultAccount () {
Account defaultUser = new Account;
defaultUser.setUser(new User());
}
}
public class User implements IUser {
public String name;
public Long id;
...
}
Summary




[...] Dependency Injection on a Project I have previously tried explaining Dependency Injection and how it can be beneficial to any project. This leads us to an [...]
Please continue discussion on the forum: link