Advanced Java (2160707)

BE | Semester-4   Winter-2018 | 20-11-2018

Q5) (b)

What is Dependency Injection?

What is Dependency Injection

  • Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application.
  • Dependency Injection makes our programming code loosely coupled
  • DI is a concept of injecting anobject into a class rather than explicitly creating object in a class, since IoC container injects object into class during runtime
  • Example:Standard code without Dependency Injection
    • public class TextEditor
      {
          private SpellChecker spellChecker;
          public TextEditor()
          {
          spellChecker = new SpellChecker();
          }
      }
  • Example:Code with Dependency Injection
    • public class TextEditor
      {
          private SpellChecker spellChecker;
          public TextEditor(SpellChecker spellChecker)
          {
          this.spellChecker = spellChecker;
          }
      }