The 3 Types of Dependency Injection (2024)

The 3 Types of Dependency Injection (1)

  • Report this article

Mohammad Ramezani The 3 Types of Dependency Injection (2)

Mohammad Ramezani

Senior Software Engineer at Knab

Published Sep 5, 2020

+ Follow

Dependency Injection solves problems such as:

  1. How can an application or class be independent of how its objects are created?
  2. How can the way objects are created be specified in separate configuration files?
  3. How can an application support different configurations?

Creating objects directly within the class is inflexible because it commits the class to particular objects and makes it impossible to change the instantiation later independently from (without having to change) the class. It stops the class from being reusable if other objects are required, and it makes the class hard to test because real objects can not be replaced with mock objects.

A class is no longer responsible for creating the objects it requires, and it does not have to delegate instantiation to a factory object as in the Abstract Factory design pattern.

There are three types of dependency injection — constructor injection, method injection, and property injection.

Constructor Injection

  • Constructor injection is the process of using the constructor to pass in the dependencies of a class.
  • You should use constructor injection when your class has a dependency that the class requires in order to work properly.
  • If your class cannot work without a dependency, then inject it via the constructor.
  • you should use constructor injection when the dependency in question has a lifetime longer than a single method. Dependencies passed into the constructor should be useful to the class in a general way, with its use spanning multiple methods in the class. If a dependency is used in only one spot, method injection
  • Checking fornull is necessary andis boilerplate code. Protecting againstnull being passed as a parameter is called theguard pattern

Property Injection (aka setter injection)

  • You should use property injection in case the dependency is truly optional
  • Property Injection however causesTemporal Couplingand when writing Line of Business applications, your dependencies should never be optional: you should instead apply theNull Object pattern.
  • property injection is considered bad in 98% of all scenarios because it hides dependencies and there is no guarantee that the object will be injected when the class is created. (ref)
  • The built-in IoC container does not support property injection. You will have to use a third-party IoC container.

Method Injection

  • Thus method injection is useful in two scenarios: when the implementation of dependency will vary, and when the dependency needs to be renewed after each use.In both cases, it’s up to the caller to decide what implementation to pass to the method.

Conclusion

Dependency injection is a powerful, useful, and critical technique to use in order to write clean, loosely coupled, easy to maintain code. There are three ways to do dependency injection, each having its own use case. Learn when to use these three techniques, and you will be well on your way to writing excellent, testable, and lovely code.

Help improve contributions

Mark contributions as unhelpful if you find them irrelevant or not valuable to the article. This feedback is private to you and won’t be shared publicly.

Contribution hidden for you

This feedback is never shared publicly, we’ll use it to show better contributions to everyone.

Like
Comment

74

5 Comments

Arifur Rahman

Manager IT Dept(Software Development Team) | .Net Core | Restful API | Microservice | SQL | DB Performance Tuning

1w

  • Report this comment

Very Nice.

Like Reply

1Reaction

Nandhakumar Selvaraj

Senior Software Engineer at Smitiv Technologies

2mo

  • Report this comment

Best Explanation. Thank you.

Like Reply

1Reaction

Elaheh Mahmoodi

Software Developer

2y

  • Report this comment

پس چرا Service Locator رو نگفتین؟

Like Reply

1Reaction

See more comments

To view or add a comment, sign in

More articles by this author

No more previous content

  • What's the Hi/Lo algorithm? Oct 14, 2020
  • Specification pattern: what’s that? Oct 13, 2020
  • Screaming Architecture Apr 8, 2020
  • Premature optimization is the root of all evil Apr 7, 2020
  • Fluent Interface: Simple Concept To Code Legibility Jan 13, 2020
  • It was announced that .NET 5 will be the next release of .NET Core and represents a unification of the platform. Dec 15, 2019
  • monolithic to microservices migration Nov 30, 2019
  • Monolith First (By Martin Fowler) Jan 31, 2019
  • Common Mistakes in Dot Net Framework Concepts (MSIL, CLI, Source Code, and managed or unmanaged Code) Jan 18, 2019
  • Can Quality Guarantee Success? Mar 25, 2017

No more next content

See all

Sign in

Stay updated on your professional world

Sign in

By clicking Continue, you agree to LinkedIn’s User Agreement, Privacy Policy, and Cookie Policy.

New to LinkedIn? Join now

Insights from the community

  • Object Oriented Design What's the best way to identify key classes and attributes in object-oriented analysis?
  • Object Oriented Design How do you debug inheritance and polymorphism issues?
  • Multithreading How do you choose the appropriate multithreading design pattern for your problem domain?
  • Object Oriented Design How do you use dependency injection and inversion of control to reduce coupling and increase security?
  • Domain-Driven Design (DDD) What are some best practices to document and visualize your domain model and its evolution?

Others also viewed

  • Modelling: Is it Art or Math Koos Brandt 4y
  • Modelling: Is it Art or Math Koos Brandt 4y
  • Build a simple DI container for Dependency Injection Ke An NGUYEN 4mo
  • Build a simple DI container for Dependency Injection Ke An NGUYEN 4mo
  • YOUser Centricity Mark Weinberg 7y
  • YOUser Centricity Mark Weinberg 7y
  • Looking back at The Unified Modeling Language (UML) Alvin Brathwaite, MSc 7y
  • Visualize Sharad Bhushan Kandikonda 3y
  • Use the Mediator design pattern Fahed Aljghine 6mo
  • Seven ways to communicate better using Box-and-Arrow diagrams Mauro Morelli 1y

Explore topics

  • Sales
  • Marketing
  • Business Administration
  • HR Management
  • Content Management
  • Engineering
  • Soft Skills
  • See All
The 3 Types of Dependency Injection (2024)
Top Articles
Which of the 4Cs Matter Most | Hearts On Fire
Top Five Easiest Fighters To Use For Beginners In MLBB | Codashop Blog PH
Scheelzien, volwassenen - Alrijne Ziekenhuis
Hotels Near 6491 Peachtree Industrial Blvd
Xre-02022
Worcester Weather Underground
Cappacuolo Pronunciation
It may surround a charged particle Crossword Clue
Belle Meade Barbershop | Uncle Classic Barbershop | Nashville Barbers
Comforting Nectar Bee Swarm
Rainbird Wiring Diagram
Professor Qwertyson
How to change your Android phone's default Google account
Www.megaredrewards.com
Gameday Red Sox
What's Wrong with the Chevrolet Tahoe?
Tripadvisor Near Me
4Chan Louisville
Summoners War Update Notes
Google Feud Unblocked 6969
Tcu Jaggaer
Images of CGC-graded Comic Books Now Available Using the CGC Certification Verification Tool
라이키 유출
Spider-Man: Across The Spider-Verse Showtimes Near Marcus Bay Park Cinema
Unterwegs im autonomen Freightliner Cascadia: Finger weg, jetzt fahre ich!
Www.paystubportal.com/7-11 Login
Lbrands Login Aces
Ncal Kaiser Online Pay
Himekishi Ga Classmate Raw
Ugly Daughter From Grown Ups
Helloid Worthington Login
Warn Notice Va
Missing 2023 Showtimes Near Mjr Southgate
Autopsy, Grave Rating, and Corpse Guide in Graveyard Keeper
Flaky Fish Meat Rdr2
Watchdocumentaries Gun Mayhem 2
Colorado Parks And Wildlife Reissue List
Srg Senior Living Yardi Elearning Login
Jewish Federation Of Greater Rochester
Hazel Moore Boobpedia
Arch Aplin Iii Felony
5103 Liberty Ave, North Bergen, NJ 07047 - MLS 240018284 - Coldwell Banker
A jovem que batizou lei após ser sequestrada por 'amigo virtual'
25100 N 104Th Way
Game Like Tales Of Androgyny
Peugeot-dealer Hedin Automotive: alles onder één dak | Hedin
28 Mm Zwart Spaanplaat Gemelamineerd (U999 ST9 Matte | RAL9005) Op Maat | Zagen Op Mm + ABS Kantenband
How Did Natalie Earnheart Lose Weight
Inside the Bestselling Medical Mystery 'Hidden Valley Road'
Asisn Massage Near Me
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5348

Rating: 4.2 / 5 (43 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.