Hello Dependency Injection!

Dare Osewa
2 min readFeb 16, 2020

--

Very early into my .NET journey, just like most people i couldn’t just get the importance of dependency injection instead of just “newing” classes all around my code.

In the middle of a mobile development project, it would happen that we needed to switch the data source of the application and then issues arose as our code was tightly coupled.

In Steve Smith’s words “Tight coupling to dependencies makes it harder to find seams in your code where you can break the system apart and isolate one part from another in order to test it. High-quality software is modular and made of loosely coupled components that can each be tested in isolation, as well as together with the rest of the system.”.

So now what is Dependency Injection and how can it help us write modular applications ?

Dependency Injection is a technique for ensuring that classes gain access to their dependent classes through a constructor or a setter method.

Consider a scenario in which a certain Class A depends on the functionalities or data provided by a non-static Class B, it is expected that Class B is instantiated before Class A can call it’s methods or access it’s properties.

Dependency Injection ensures that the instantiation of Class B is abstracted to a Dependency Injection Container while Class A simply focuses on using Class B’s functionalities. Apart from ensuring that your application is highly modular and unit testable, Dependency Injection also ensures that swapping implementations is easier when your requirements change.

One thing to also note is that even though Dependency Injection has some relationship with Dependency Inversion even though they differ. A follow-up article to this one will be about Dependency Inversion.

--

--