Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How is constructor injection used in dependency injection?


Asked by Zachary Dougherty on Dec 02, 2021 FAQ



Construction injection is a type of Dependency Injection where dependencies are provided through a constructor. Visit the Dependency Injection chapter to learn more about it. We learned about the Resolve () method in the previous chapter.
In addition,
The intent of Dependency Injection is to make code maintainable . Dependency Injection helps to reduce the tight coupling among software components. Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.
Just so, Dependency Injection is a design pattern whereon object provides another object with dependencies. So the easiest way to understand it to to use an example. But let’s first understand what dependency means. Well, dependency means something needs something else to function. For example, a computer needs a hard disk, keyboard, memory etc.
Likewise,
A constructor therefore enforces the dependency requirement. But if it makes sense for the class to be able to do its job without using the dependency, you could use property injection. When using property injection the dependency may or may not used depending on whether the property is actually invoked.
In fact,
Use constructor injection for the mandatory dependencies and setter injection for optional dependencies. (Here mandatory dependency is the one without which the main business logic wouldn’t work and optional dependencies are the ones which if null doesn’t hamper the main business logic.)