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
Click to Enlarge