What Is Dependency Injection
In this artcile we will learn about Dependency Injection & will follow this up with one more article on how to implement dependency injection using Microsoft Unity Application Block.
Dependency Injection is a design pattern in which dependency of object is injected by framework rather than created by Object itself. Dependency injection is a software design pattern that implements inversion of control (IOC).
In case you are not familiar with IOC I would suggest you to read this article "Inversion of Control (IOC) Pattern" , Knowing IOC is a prerequisite for learning Dependency Injection as Dependency Injection is just one of the techniques to implement IOC ( Inversion of Control ).
What is dependency, You have a class which depends on object of another calss for it to function. In the below example DataAccessLayer Class required an Object of MSSQL class to read data from an MS SQL database. DataAccessLayer Class has a dependency on object of MSSQL class to funtion. Basic question is what and how do I provide to the dependant class to make it to work ?.
What Is Dependency Injection
Literal meaning is to inject dependency. The Ability to supply ( Inject ) an external dependency into a software component.
What Do U Mean By Injecting Dependency?
In the ablove sample you are creating an instance of In the data access layer class which is wrong. What you are needed to do is to Inject the dependent object ( in this case object of MSSQL class ) to the class ( DataAccessLayer ) using the constructor from the outside.
Injection can be done using constructor like showing in the above code or via a setter or Method.
Types Of Dependency Injection
Constructor Injection is the best and most widely used..
Advantages & Disadvantages
- Loosely Coupled
- Much Better Testability
- Sepration Of Concerns
- Allows Use of IOC Container
- Increase Code Complexity
- Difficult to Understand,
- Complicates Debugging & Code Flow. Dependency injection can make code difficult to trace (read) because it separates behavior from construction. This means developers must refer to more files to follow how a system perform
- Requires more lines of code to accomplish the same behavior legacy code would
- Diminishes encapsulation by requiring users of a system to know how it works and not merely what it does
How To Construct The Dependency ?
To construct dependencis of a class we have something called as the Dependency Injuction Container. Container is a map of dependencies and logic to create the dependcies which are required by your class . When you ask for a dependency the Container look for a depedency in the collection, see if its already created if the dependency is already created it will return that dependency, otherwise it will create it stored it and then return the depency. Here I am using singlton for the above. The main advantage of using a container is it can resolve complex dependencies transparently.