What is Dependency Injection

Dependency Injection is often being used when you want to decouple your components from each other, such that exchanging implementation later becomes easy. It is based upon interfaces, combined with an “instantiation trick”, that allows you to declare anywhere you wish what implementation class to use whenever somebody for some reasons needs a class implementing some interface. The Ninject website easily explains this using the idea of a Samurai that needs an IWeapon, implying that the Samurai can use any type of weapon, and that he doesn’t care about what weapon he is given.

If you look at my Magic for instance, you will notice that I exclusively pass in my services as interfaces, to my controllers. Then I bind my interfaces to some implementation class using Ninject. This allows me to exchange my business logic, if I need to do that later, without modifying my original service class. For instance, I might later need to cache parts of my database access, at which point I can simply create an ITodoCacheService, implement ITodoService on it, and make sure I bind ITodoService towards ITodoCacheService. This avoids forcing me to change the logic of my original ITodoService, yet still use my new cached ITodoService where ever I need caching.

Then when ever I need an implementation of ITodoService, I don’t create it directly, but rather request it from Ninject, through something such as “Kernel.Get()”, instead of creating my instance directly, which makes sure I get the correct implementation class every time, according to my bindings.

Dependency Injection is crucial for any large scale real world app, due to its ability to decouple your implementations, resulting in higher amount of “encapsulation”. This blog was written as a consequence of somebody asking me the question in the header, and I realised that few junior developers actually understands this crucial concept – Hence, I wanted to write up something about it, in an attempt at trying to teach something important, to those needing to understanding the concept.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.