Dependency Injection ensures that high level object is independent of low level object. In conventional programming modules dependency relationships are imagined as high level objects directly related to low level objects. But the dependency injection pattern inverse the conventional dependency as if high level objects is independent of low level objects. This type of inversion is called IOC (Inversion of Control) that is dependency inversion principle. High level object should depend on low level object through an Interface that is Interface is acting here as a gateway of object dependencies between high level object and low level object. Both the high level and low level object should depend on the Interface but the Interface depends on none but abstractions.
This kind of design pattern or principle brings the software modules decoupled, reusable, testable and maintainable. Here high level object uses the instance of the Interface in a way of constructor injection on the other hand low level object implements the Interface in a way of interface implementation.
Please consider the following example(in C#) to gain clarification:
1 public class HighLevelObject
2 {
3 public HighLevelObject(IObjectGateway obj)
4 {
5 obj.WriteToLog("New object is created");
6 }
7 }
8
9 public interface IObjectGateway
10 {
11 void WriteToLog(string text);
12 }
13
14 public class LowLevelObject: IObjectGateway
15 {
16 public void WriteToLog(string text)
17 {
18 Console.WriteLine(text);
19 }
20 }
21
22 HighLevelObject hlo = new HighLevelObject (new LowLevelObject());
Feel free to leave any comments for clarification, changes, or improvements. Also, you can contact with iXora Solution expert teams for any consultation or coordination from here.
Add a Comment