SlideShare a Scribd company logo
1 of 21
HOW TO IMPLEMENT DEPENDENCY INJECTION IN
C#?
PROBLEM SCENARIO
 Objects can be loosely or tightly coupled. Tightly coupled objects have dependencies on
concrete objects due to which they have lower reusability, maintainability, and testability.
Tightly coupled object provide lesser dynamicity due to which user need to change the
implementation of class and it’s member functions. We can achieve this via Dependency
Injection.
WHAT DEPENDENCY INJECTION DO?
 Irrelevant dependencies increase code complexity which results in increased loading and
execution time of application. Dependency Injection (DI) is a solution design which
provides development of the loosely coupled code. ‘Loose Coupling‘ means the object will
only have those dependencies which are required to do their work. Loosely coupled code
increases the modularity of application which offers us greater reusability, maintainability,
and testability.
 Note: For more details on loosely coupled coding guidelines, please follow Dependency
Inversion Principle.
TYPES OF DEPENDENCY INJECTION
 In general, there are three types of DI,
1. Constructor Injection
2. Property or Setter Injection
3. Method Injection
CONSTRUCTION INJECTION
 It uses parameters to inject dependencies. The object has no defaults or single
constructor due to which specified values are required at the time of creation to instantiate
the object. This is the most common type of DI. We can use injected component anywhere
in the class. It makes a strong dependency contract.
 In this type, we can make dependency immutable in order to prevent it from circular
dependency. For entire dependency graph, it requires up-front wiring which needs a
public constructor in the class to pass dependency as a parameter.
CONSTRUCTION INJECTION EXAMPLE
 Consider a scenario, where a student took admission in school and school provides bag,
dress, books etc to that student. Here, the student does not like to receive goodies from
different counters. What the student would like, that he/she should receive all the goodies
from a single counter in one go.
 Create a console application of any name and create two classes. See below image.
 In above image, SchoolBag and SchoolDress are the basic ‘Service classes’ having Bag
and Dress methods respectively.
 In the image below, Student class is ‘Client class’ using the service (i.e. SchoolBag ) and
assigning that bag to ‘John’ in the main program.
 The Student constructor is assigning a new instance of SchoolBag class. And the Assign
method is acting like a Service_Start() method. It is receiving the studentName from the
main program and passing it to Bag method of SchoolBag class.
OUTPUT
The output of above implementation will be,
 Above implementation has one issue i.e. we only managed to assign SchoolBag to the
Student. SchoolDress is still left or what if we want to provide some other things to the
student. Since the object of SchoolBag is created inside the Student class’s constructor,
we have to modify the implementation of Student class for SchoolDress and the for some
other thing, which is not a proper implementation. This is a type of concrete dependency.
To avoid this, we can use interfaces to provide a level of indirection. See the below
implementation.
IMPLEMENTING INTERFACE
 Create a service interface.
interface IThings
{
void Assign(string studentName);
}
and now remove the previous implementation of the service classes (i.e. SchoolBag and
SchoolDress ) and implement the above service interface in the service classes. Like this,
After this, we need to alter our client class. We need to “inject” a parameter of service
interface type (i.e. IThings ) in the constructor of Student class.
In above image, we have injected a new object into the client class. And we can use this
object anywhere in the client class. Below is the respective output.
SETTER or PROPERTY INJECTION
 In this, we don’t require to change the constructor. We pass dependencies through the
exposed public properties. In this, we can create costly resources or services as late as
possible and only when required. It is difficult to identify which dependencies are required
and it is beneficial to perform null checks in setter properties. For entire dependency
graph, it does not require up-front wiring.
 In addition to our previous code, the implementation we did for Student constructor has
now been transferred to the setter of SetStudent property. And the new object which was
previously passed as a parameter in the constructor of Student class, has now been
assigned to the SetStudent property in the main program. The output will be same as it
was for constructor injection. See the following image.
METHOD INJECTION
 In this, the dependency is been injected within a single method to be used by that method
only. It is useful in case when only one method needs dependency, not the whole class.
 In addition to our previous code, the implementation we did for setter property has now
been transferred to the Assign method and the dependency has been injected as a
parameter from main program. The output will be same as it was for property injection.
See the following image.
BENEFITS OF USING DEPENDENCY INJECTION
 With DI, you can inject extra code between the conditions. To illustration, you can utilize
the Constructor Injection to give an instance its conditions. In the event that you have a
class with ten functions that have no dependencies. Then, you have to include one or
more than one function with a dependency. You can change the constructor to utilize
Constructor Injection.
 Then again, you can basically include another constructor that takes the dependency as a
parameter. However, in the event that there is a dependency which is costly to make, you
can utilize the Setter Injection. It gives you a chance to make the expensive resources
only when required. As should be obvious, DI makes code testable, viable, reusable and
coherent.
References
https://www.loginworks.com/technical-blogs/implement-dependency-
injection-c/

More Related Content

What's hot

Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & CompositeSarath C
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Patterneprafulla
 
Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Sameer Rathoud
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Patternmelbournepatterns
 
Design Patterns - 04 Adapter and Facade Pattern
Design Patterns - 04 Adapter and Facade PatternDesign Patterns - 04 Adapter and Facade Pattern
Design Patterns - 04 Adapter and Facade Patterneprafulla
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patternsGomathiNayagam S
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - AdapterManoj Kumar
 
Lecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design PatternsLecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design Patternsop205
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with javaRajiv Gupta
 

What's hot (20)

Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Design patterns - Proxy & Composite
Design patterns - Proxy & CompositeDesign patterns - Proxy & Composite
Design patterns - Proxy & Composite
 
Sda 8
Sda   8Sda   8
Sda 8
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Design Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight PatternDesign Patterns - 03 Composite and Flyweight Pattern
Design Patterns - 03 Composite and Flyweight Pattern
 
Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Pattern
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
 
Factory method pattern
Factory method patternFactory method pattern
Factory method pattern
 
Design Patterns - 04 Adapter and Facade Pattern
Design Patterns - 04 Adapter and Facade PatternDesign Patterns - 04 Adapter and Facade Pattern
Design Patterns - 04 Adapter and Facade Pattern
 
Javascript design patterns
Javascript design patternsJavascript design patterns
Javascript design patterns
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - Adapter
 
Lecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design PatternsLecture 5 Software Engineering and Design Design Patterns
Lecture 5 Software Engineering and Design Design Patterns
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 

Similar to How to implement dependency injection in c#

Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast trackBinu Bhasuran
 
Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Mohammed Salah Eldowy
 
Dependency injection using dagger 2
Dependency injection using dagger 2Dependency injection using dagger 2
Dependency injection using dagger 2Mahmoud El-Naggar
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionKnoldus Inc.
 
Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2Sanket Shah
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversionchhabraravish23
 
Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Knoldus Inc.
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#Aditya Kumar Rajan
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NETssusere19c741
 
Dependency injection using Google guice
Dependency injection using Google guiceDependency injection using Google guice
Dependency injection using Google guiceAman Verma
 
Leveling up with AngularJS
Leveling up with AngularJSLeveling up with AngularJS
Leveling up with AngularJSAustin Condiff
 

Similar to How to implement dependency injection in c# (20)

Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast track
 
Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)Clearing confusion about IoC (Inversion of Control)
Clearing confusion about IoC (Inversion of Control)
 
Dependency injection using dagger 2
Dependency injection using dagger 2Dependency injection using dagger 2
Dependency injection using dagger 2
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Android Dagger 2
Android  Dagger 2Android  Dagger 2
Android Dagger 2
 
Guice
GuiceGuice
Guice
 
Guice
GuiceGuice
Guice
 
Dependency injection and inversion
Dependency injection and inversionDependency injection and inversion
Dependency injection and inversion
 
Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)Introduction to dependency injection in Scala (Play)
Introduction to dependency injection in Scala (Play)
 
Learning solid principles using c#
Learning solid principles using c#Learning solid principles using c#
Learning solid principles using c#
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
 
17612235.ppt
17612235.ppt17612235.ppt
17612235.ppt
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Guice
GuiceGuice
Guice
 
Guice
GuiceGuice
Guice
 
sfdsdfsdfsdf
sfdsdfsdfsdfsfdsdfsdfsdf
sfdsdfsdfsdf
 
Dependency injection using Google guice
Dependency injection using Google guiceDependency injection using Google guice
Dependency injection using Google guice
 
Leveling up with AngularJS
Leveling up with AngularJSLeveling up with AngularJS
Leveling up with AngularJS
 

Recently uploaded

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 

Recently uploaded (20)

(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

How to implement dependency injection in c#

  • 1. HOW TO IMPLEMENT DEPENDENCY INJECTION IN C#?
  • 2. PROBLEM SCENARIO  Objects can be loosely or tightly coupled. Tightly coupled objects have dependencies on concrete objects due to which they have lower reusability, maintainability, and testability. Tightly coupled object provide lesser dynamicity due to which user need to change the implementation of class and it’s member functions. We can achieve this via Dependency Injection.
  • 3. WHAT DEPENDENCY INJECTION DO?  Irrelevant dependencies increase code complexity which results in increased loading and execution time of application. Dependency Injection (DI) is a solution design which provides development of the loosely coupled code. ‘Loose Coupling‘ means the object will only have those dependencies which are required to do their work. Loosely coupled code increases the modularity of application which offers us greater reusability, maintainability, and testability.  Note: For more details on loosely coupled coding guidelines, please follow Dependency Inversion Principle.
  • 4. TYPES OF DEPENDENCY INJECTION  In general, there are three types of DI, 1. Constructor Injection 2. Property or Setter Injection 3. Method Injection
  • 5. CONSTRUCTION INJECTION  It uses parameters to inject dependencies. The object has no defaults or single constructor due to which specified values are required at the time of creation to instantiate the object. This is the most common type of DI. We can use injected component anywhere in the class. It makes a strong dependency contract.  In this type, we can make dependency immutable in order to prevent it from circular dependency. For entire dependency graph, it requires up-front wiring which needs a public constructor in the class to pass dependency as a parameter.
  • 6. CONSTRUCTION INJECTION EXAMPLE  Consider a scenario, where a student took admission in school and school provides bag, dress, books etc to that student. Here, the student does not like to receive goodies from different counters. What the student would like, that he/she should receive all the goodies from a single counter in one go.  Create a console application of any name and create two classes. See below image.
  • 7.
  • 8.  In above image, SchoolBag and SchoolDress are the basic ‘Service classes’ having Bag and Dress methods respectively.  In the image below, Student class is ‘Client class’ using the service (i.e. SchoolBag ) and assigning that bag to ‘John’ in the main program.
  • 9.
  • 10.  The Student constructor is assigning a new instance of SchoolBag class. And the Assign method is acting like a Service_Start() method. It is receiving the studentName from the main program and passing it to Bag method of SchoolBag class. OUTPUT The output of above implementation will be,
  • 11.  Above implementation has one issue i.e. we only managed to assign SchoolBag to the Student. SchoolDress is still left or what if we want to provide some other things to the student. Since the object of SchoolBag is created inside the Student class’s constructor, we have to modify the implementation of Student class for SchoolDress and the for some other thing, which is not a proper implementation. This is a type of concrete dependency. To avoid this, we can use interfaces to provide a level of indirection. See the below implementation.
  • 12. IMPLEMENTING INTERFACE  Create a service interface. interface IThings { void Assign(string studentName); } and now remove the previous implementation of the service classes (i.e. SchoolBag and SchoolDress ) and implement the above service interface in the service classes. Like this,
  • 13. After this, we need to alter our client class. We need to “inject” a parameter of service interface type (i.e. IThings ) in the constructor of Student class.
  • 14.
  • 15. In above image, we have injected a new object into the client class. And we can use this object anywhere in the client class. Below is the respective output.
  • 16. SETTER or PROPERTY INJECTION  In this, we don’t require to change the constructor. We pass dependencies through the exposed public properties. In this, we can create costly resources or services as late as possible and only when required. It is difficult to identify which dependencies are required and it is beneficial to perform null checks in setter properties. For entire dependency graph, it does not require up-front wiring.  In addition to our previous code, the implementation we did for Student constructor has now been transferred to the setter of SetStudent property. And the new object which was previously passed as a parameter in the constructor of Student class, has now been assigned to the SetStudent property in the main program. The output will be same as it was for constructor injection. See the following image.
  • 17.
  • 18. METHOD INJECTION  In this, the dependency is been injected within a single method to be used by that method only. It is useful in case when only one method needs dependency, not the whole class.  In addition to our previous code, the implementation we did for setter property has now been transferred to the Assign method and the dependency has been injected as a parameter from main program. The output will be same as it was for property injection. See the following image.
  • 19.
  • 20. BENEFITS OF USING DEPENDENCY INJECTION  With DI, you can inject extra code between the conditions. To illustration, you can utilize the Constructor Injection to give an instance its conditions. In the event that you have a class with ten functions that have no dependencies. Then, you have to include one or more than one function with a dependency. You can change the constructor to utilize Constructor Injection.  Then again, you can basically include another constructor that takes the dependency as a parameter. However, in the event that there is a dependency which is costly to make, you can utilize the Setter Injection. It gives you a chance to make the expensive resources only when required. As should be obvious, DI makes code testable, viable, reusable and coherent.