Articles → .NET DESIGN PATTERN → Dependency Injection In C#

Dependency Injection In C#






Purpose Of Dependency Injection





Constructor Injection




public class MyClass {
  public void display() {
    Console.WriteLine("Display Function for MyClass");
  }
}

public class TighlyCoupledCode {
  public void CallMethod() {
    MyClass myClass = new MyClass();
    myClass.display();
  }
}




public class MyClass {
  public void display() {
    Console.WriteLine("Display Function for MyClass");
  }
}

public class LooselyCoupledCode {
  MyClass _myClass;
  public LooselyCoupledCode(MyClass myClass) {
    this._myClass = myClass;
  }
  public void CallMethod() {
    _myClass.display();
  }
}





Calling The LooselyCoupledCode Class




// Step 1: Create an instance of MyClass
MyClass myClass = new MyClass();

// Step 2: Create an instance of LooselyCoupledCode, passing myClass
LooselyCoupledCode looselyCoupledCode = new LooselyCoupledCode(myClass);

// Step 3: Call the CallMethod to execute the display method
looselyCoupledCode.CallMethod();



Output


Picture showing the output of dependency injection in C#
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Monday, December 28, 2020
 
Updated On  -  Monday, October 23, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250