Skip to content
Fix Code Error

What is dependency injection?

March 13, 2021 by Code Error
Posted By: AR

There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,

What is dependency injection and when/why should or shouldn’t it be used?

Solution

Dependency Injection is passing dependency to other objects or framework( dependency injector).

Dependency injection makes testing easier. The injection can be done through constructor.

SomeClass() has its constructor as following:

public SomeClass() {
    myObject = Factory.getObject();
}

Problem:
If myObject involves complex tasks such as disk access or network access, it is hard to do unit test on SomeClass(). Programmers have to mock myObject and might intercept the factory call.

Alternative solution:

  • Passing myObject in as an argument to the constructor
public SomeClass (MyClass myObject) {
    this.myObject = myObject;
}

myObject can be passed directly which makes testing easier.

  • One common alternative is defining a do-nothing constructor. Dependency injection can be done through setters. (h/t @MikeVella).
  • Martin Fowler documents a third alternative (h/t @MarcDix), where classes explicitly implement an interface for the dependencies programmers wish injected.

It is harder to isolate components in unit testing without dependency injection.

In 2013, when I wrote this answer, this was a major theme on the Google Testing Blog. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.

Answered By: wds

Related Articles

  • UnsatisfiedDependencyException: Error creating bean…
  • Error 'Map', but got one of type 'Null' flutter web…
  • Spring Boot - Cannot determine embedded database…
  • org.springframework.beans.factory.BeanCreationExcept…
  • Injection of autowired dependencies failed;
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • Spring data jpa- No bean named…
  • Vue.JS & Spring Boot - Redirect to homepage on 404
  • Error creating bean with name
  • Eclipse will not start and I haven't changed anything
  • Creating nested dicts with dynamic key and values
  • Gradle error: Execution failed for task…
  • Requested bean is currently in creation: Is there an…
  • AngularJS : Factory and Service?
  • Error: container has not been made global - how to solve?
  • What are the differences between Abstract Factory…
  • error LNK2005: ✘✘✘ already defined in…
  • JavaScript unit test tools for TDD
  • How to test Spring Data repositories?
  • Unit Testing C Code
  • org.gradle.api.tasks.TaskExecutionException:…
  • C++ code generating errors LNK2005 & LNK1169 on VS2019
  • Why is Future[Set[Unit]] not accepted as Future[Unit]?
  • How to check for null in a single statement in scala?
  • JPA Hibernate Persistence exception…
  • How to implement the factory method pattern in C++ correctly
  • AngularJS : When to use service instead of factory
  • What is unit testing and how do you do it?
  • firebase storage java.lang.IllegalStateException:…
  • npm install error in vue
  • How to detect change in a property of an object in…
  • AngularJS: Service vs provider vs factory
  • org.springframework.beans.factory.UnsatisfiedDepende…
  • template repeat in template repeat
  • Laravel 5: Updating Multiple Records
  • vuejs Data property undefined
  • 'int' object has no attribute 'user_list'. (Django…
  • Testing aurelia customElement with bindable and dependencies
  • How can I test an AngularJS service from the console?
  • How to filter a RecyclerView with a SearchView
  • Execution failed for task…
  • "Uncaught TypeError: undefined is not a function" -…
  • Understanding component props in VueJS
  • Spring Boot with ElasticSearch in Groovy: WebClient…
  • RecursionError: maximum recursion depth exceeded in…
  • Reference - What does this regex mean?
  • Spring Boot application context interferes with…
  • What are containers in Aurelia Dependency Injection
  • VUE Error when run test unit
  • How do I implement IEnumerable
  • How do I create a singleton service in Angular 2?
  • How to get response from S3 getObject in Node.js?
  • What is a smart pointer and when should I use one?
  • Could not resolve placeholder in string value
  • Vaadin Spring Boot - There was an exception while…
  • map function for objects (instead of arrays)
  • Aurelia bundling issue with virtual directory
  • Getting error "Failed to mount component: template…
  • Logging best practices
  • No matching bean of type ... found for dependency
  • Why does Spring security throw exception…
  • What's the difference between unit, functional,…
  • What does T&& (double ampersand) mean in C++11?
  • Nested class: Calling child class properties in parent class
  • Verify a method call using Moq
  • What does AngularJS do better than jQuery?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How to re render component once store data is…
  • Autowiring fails: Not an managed Type
  • Dynamically change bootstrap progress bar value when…
  • Injecting $scope into an angular service function()
  • What are the real-world strengths and weaknesses of…
  • How to update or insert to import using typescript…
  • LINQ where clause with lambda expression having OR…
  • Typescript es6 import module "File is not a module error"
  • Java.lang.NoClassDefFoundError:…
  • How can I use/create dynamic template to compile…
  • The definitive guide to form-based website authentication
  • Difference between by viewmodels and viewmodel…
  • What is the copy-and-swap idiom?
  • Call method from another component in Vue.js
  • How to write unit testing for Angular / TypeScript…
  • Check for internet connection with Swift
  • How to test that no exception is thrown?
  • Which .NET Dependency Injection frameworks are worth…
  • How does PHP 'foreach' actually work?
  • during wct test: Failed to load resource: the server…
  • Sort objects in ArrayList by date?
  • Memcached vs. Redis?
  • Error creating bean with name 'entityManagerFactory'…
  • Tomcat 7 "SEVERE: A child container failed during start"
  • Why does C++ code for testing the Collatz conjecture…
  • Start redis-server with config file
  • Spring Boot - Error creating bean with name…
  • Unable to use helper classes within unit tests of a…
  • How to connect to a docker container from outside…
  • getting error while updating Composer
  • Why does one use dependency injection?
  • What's the best way of scraping data from a website?
  • For-each over an array in JavaScript

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

JavaScript: How do I print a message to the error console?

Next Post:

How to determine if Javascript array contains an object with an attribute that equals a given value?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error