Why Dependency Injection?

Hi Friends,

I have been recently asked by one of my book readers on twitter, why you applied Dependency Injection (DI) in controller? Below is the tweet for the same. Below is the glimpse of the same.

Let me start with why DI? Below is the code structure for the same, If I would not be using DI.

At first place, it looks ugly. Also, there is no limitation on that, let’s say you have more deep rooted dependency, then in that case for creating the instance for the same, you would have been delving further more, which makes code very tightly coupled. When, I say tightly coupled, it means in this case, your code couldn’t be tested as we follow the pattern in TDD (Test Driven Development).

However, using DI, making sure all the dependencies are getting resolved automatically with the required framework, doesn’t matter which DI framework you are using. Below, is the config file for the same.

Here, in the above snippet, you can see that I have registered all the required dependencies at one place and in that constructor with a simple interface, I am achieving my end result. With this concept in place, I can easily mock the data as well and supply the same here to test my code.

I hope you would have liked this discussion for the need of DI in application. Also, this example is from MVC 5 – SPA app. In ASP.NET Core, DI is built in, hence we don’t actually need any third party framework for achieving the same.

Rahul Sahay
Happy Coding