Introduction
Dependency Injection (DI) is a software design pattern that allows us to develop loosely-coupled code. The purpose of DI is to make code maintainable and easy to update.
Loosely coupling means that two objects are independent. If we change one object then it will not affect the other.
Types of Dependency Injection Design Pattern in C#,
- Constructor Injection
- Property Injection
- Method Injection
Constructor Injection
Dependency Injection is done through the class’s constructor when creating the instance of that class.
It is used frequently.
Example
- using System;
-
- namespace ConsoleApp1
- {
-
- public interface IService
- {
- void Print();
- }
-
- public class Service1 : IService
- {
- public void Print()
- {
- Console.WriteLine("Print Method 1");
- }
- }
-
- public class Service2 : IService
- {
- public void Print()
- {
- Console.WriteLine("Print Method 2");
- }
- }
-
- class ClassA
- {
- private IService _service;
- public ClassA(IService service)
- {
- this._service = service;
- }
- public void PrintMethod()
- {
- this._service.Print();
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Service1 s1 = new Service1();
-
- ClassA c1 = new ClassA(s1);
- c1.PrintMethod();
- Service2 s2 = new Service2();
-
- c1 = new ClassA(s2);
- c1.PrintMethod();
- Console.ReadLine();
- }
- }
- }
- **********End**************
Property Injection
Dependency Injection is done through the public property.
From the above example, it is required to modify the below two classes.
Example
- class ClassA
- {
- private IService _service;
- public IService Service
- {
- set
- {
- this._service = value;
- }
- }
- public void PrintMethod()
- {
- this._service.Print();
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Service1 s1 = new Service1();
- ClassA c1 = new ClassA();
-
- c1.Service = s1;
- c1.PrintMethod();
- Service2 s2 = new Service2();
-
- c1.Service = s2;
- c1.PrintMethod();
- Console.ReadLine();
- }
- }
- **********End**************
Method Injection
It injects the dependency into a single method to be utilized by that method.
It could be useful where the whole class does not need dependency, only one method having that dependency. This is why it is used rarely.
Modify the two classes again.
Example
- class ClassA
- {
-
- private IService _service;
- public void PrintMethod(IService service)
- {
- _service = service;
- this._service.Print();
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Service1 s1 = new Service1();
- ClassA c1 = new ClassA();
-
- c1.PrintMethod(s1);
- Service2 s2 = new Service2();
-
- c1.PrintMethod(s2);
- Console.ReadLine();
- }
- }
Many Dependency Injection containers are available in the market which implements the dependency injection design pattern.Few of them are,
- Structure Map.
- Unity
- Spring.Net
- Castle Windsor
Happy Learning...