It has been a buzz word for some intermediate level C# developers, ‘Dependency Injection’ is sometimes really hard to understand because we couldn’t understand the need for it.
In simple words, think about the scenario where you are developing an application which saves some data in a file and that file handling. You might code something like below initially
Here we are defining
- Which file to communicate (fileName)
- Where to access the file and (the file path which is appended in fileName)
- How to access it (other params of the fs object)
Then think about what if we suddenly think we are not going to write this on a File instead we are going for SQLite or some other options. So, it need a complete rewrite of this right. Its ideally something like “We are changing a lot of code in the client”. Here client is that who leverages the service from the file (or DB, in the new (future) scenario).
To handle this scenario there are two common practices.
- In client embed the logic of locating the service
- Tell the client about some dependency and make an external code which will help the client to find the service.
Both of these are more similar. Its like to achieve practice 1, one easier option is to use practice 2. So we call this as “Dependency Injection” and that extra code we call as “Dependency Injection Framework”. Things like Spring Framework and Hivemind dose the “Dependency Injection Framework” role. Scott Hanselman has a list of them for .NET.
IoC vs DI
IoC, Inversion of Control, people confuse this with Dependency Injection. But understand IoC is a generic team, meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.
DI is a form of IoC, it is a solid term, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.
Yeah each CPU architecture performs separate functions to perform same functionality. But just think about we are changing the CPUArchitecture to another in future.
This is a type of a Dependency Injection we call it as Constructor Injection. But this is clear enough to demonstrate the need of why we should inject the dependencies. Hope to meet you with another post with Advanced DI.