iXora Custom Software Development Blog

Read | Practice | Advance

What Dependency Injection Is Actually Meant For?

Posted by on in Blog
  • Font size: Larger Smaller
  • Hits: 2206
  • 0 Comments

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:

public class HighLevelObject
{
    public HighLevelObject(IObjectGateway obj)
    {
        obj.WriteToLog("New object is created");
    }
}

public interface IObjectGateway
{
    void WriteToLog(string text);
}

public class LowLevelObject: IObjectGateway
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}

HighLevelObject hlo = new HighLevelObject (new LowLevelObject()); 
Rate this blog entry:
1

Comments

  • No comments made yet. Be the first to submit a comment

Leave your comment

Guest
Guest Tuesday, 11 August 2020