03 August 2016

Dependency Injection


Dependency injection provides the objects that an object needs (dependencies) rather than constructing them itself. Dependency injection uses the dependency inversion principle of code depending upon abstractions (usually an interface) rather than directly depending upon the dependency (Ferrara 2013). A developer no longer needs to instantiate with the new operator from inside of the class. Instead, it can be taken as a constructor parameter or via a setter (Ferrara 2013). Whilst containers are no longer needed with dependency injection, they do make life a lot easier for the developer. Dependency injection containers are a map of dependencies the class needs. The container will also have the logic to create dependencies that haven't been created yet. So instead of creating the classes yourself, you can ask the container for new instances (Ferrara 2013). Dependency injection promotes loose coupling between modules to provide a way to switch code modules being used without the need to build and restart the entire application or parts of it. This could be done by using either a configuration file or by reading dependency injection information from a database table (Jhangra 2016).
 

A benefit of using dependency injection design pattern is that it enables you to ask the container for new instances of a class, saving you from creating them yourself. A developer can also inject additional code between dependencies, for example, validation logic, which saves the developer from having to write this logic for every class. Another benefit of using dependency injection design pattern is that it can make testing a lot easier. Dependency injection allows the developer to replace complex dependencies, such as databases, with mocked implementations of those dependencies, allowing you to isolate the code being tested (Culp 2011).
By using dependency injection, you are able to write cleaner and more efficient code, that is easier to read, easier to test, and easier to modify in the future.

References

Culp A, June 2011, Microsoft, accessed 15th August 2016
 
Ferrara A, 9 January 2013, online video, accessed 3rd August 2016

Jhangra N, 16 June 2016, Code Project, accessed 3rd August 2016-08-17

Helpful link
Shimoon A, 14 October 2015, dotnetliberty, online video, accessed 3rd August

No comments:

Post a Comment