Implementation of Dependency Injection Pattern in C#

Implementation of Dependency Injection Pattern in C#

Dependency Injection (DI) is a method in software design that helps us create code that's not too closely connected. It's like separating different parts of your code, so they don't rely too much on each other. This helps you handle changes and make your code easier to maintain.

In Dependency Injection, we use a builder object to set up objects and give them the things they need to work. It's like giving an object what it needs to function from outside, instead of having it figure things out on its own.

In this article, I will explain three ways to implement DI:


1- Constructor Injection

1- This is a widely used way to implement DI.

2- Dependency Injection is done by supplying the DEPENDENCY through the class’s constructor when creating the instance of that class.

3- The injected component can be used anywhere within the class.

4- Recommended to use when the injected dependency, you are using across the class methods.

5- It addresses the most common scenario where a class requires one or more dependencies.

public interface IProduct{
 void Buy();
}
public class Product1: IProduct {
 public void Buy() { 
 Console.WriteLine("Product1 Called"); 
 }
}
public class Product2: IProduct {
 public void Buy() { 
 Console.WriteLine("Product2 Called"); 
 }
}
public class ProductController{
 private IProduct _product;
 public ProductController(IProduct product) {
 this._product = product;
 }
 public BuyMethod() { 
 this._product.Buy(); 
 }
}        
class Program
{
 static void Main(string[] args)
 {
 //creating object
 Product1 p1 = new Product1(); 
 //passing dependency
 ProductController PC= new ProductController(p1);
 //TO DO:
 PC.BuyMethod();
 
 Product2 p2 = new Product2(); 
 //passing dependency
 PC = new ProductController(p2);
 //TO DO:
 PC.BuyMethod();
 }
}        

The Injection happens in the constructor, bypassing the Product that implements the IProduct Interface. The dependencies are assembled by a "Builder" and the Builder responsibilities are as follows:

1- Knowing the types of each IProduct

2- According to the request, feed the abstract IProduct to the ProductController


2- Property/Setter Injection

1- Recommended using when a class has optional dependencies, or where the implementations may need to be swapped.

2- Different logger implementations could be used in this way.

3- Does not require the creation of a new object or modifying the existing one. Without changing the object state, it could work.

public interface IProduct {
 void Buy();
}
public class Product1 : IProduct{
 public void Buy() { 
 Console.WriteLine("Product1 Called"); 
 }
}
public class Product2 : IProduct {
 public void Buy() { 
 Console.WriteLine("Product2 Called"); 
 }
}
public class ProductController{
 private IProduct _product;
 public IProduct Product {
 set { this._product = value; }
 }
 public BuyMethod() { 
 this._product.Buy(); 
 }
}        
class Program
{
 static void Main(string[] args)
 {
 //creating object
 Product1 p1 = new Product1(); 
 
 ProductController PC = new ProductController();
 PC.Product = p1; //passing dependency
 //TO DO:
 PC.BuyMethod();

 Product2 p2 = new Product2(); 
 PC.Product = p2; //passing dependency
 //TO DO:
 PC.BuyMethod();
 }
}        


3- Method Injection

1- Inject the dependency into a single method and generally for the use of that method.

2- It could be useful, where the whole class does not need the dependency, only one method having that dependency.

3- This is the way is rarely used.

public interface IProduct {
 void Buy();
}
public class Product1 : IProduct {
 public void Buy() { 
 Console.WriteLine("Product1 Called"); 
 }
}

public class Product2 : IProduct {
 public void Buy() { 
 Console.WriteLine("Product2 Called"); 
 }
}        
class Program
{
 static void Main(string[] args)
 {
 //creating object
 Product1 p1 = new Product1(); 
 
 ProductController PC = new ProductController(); 
 //TO DO:
 PC.BuyMethod(p1);

 Product2 p2 = new Product2(); 
 PC.BuyMethod(p2);
 }
}        

Advantages of Dependency Injection

1- Reduces class coupling

2- Increases code reusability

3- Improves code maintainability

4- Make unit testing possible

要查看或添加评论,请登录

Nadim Attar的更多文章

  • Task.WhenEach

    Task.WhenEach

    Are you ready to take your asynchronous programming to the next level? With the release of .NET 9, we now have – a…

  • Exploring the Exciting New Features in C# 13

    Exploring the Exciting New Features in C# 13

    C# continues to evolve, making development more efficient and expressive. With the upcoming release of C# 13, several…

  • Understanding the IGNORE_DUP_KEY Feature in SQL Server

    Understanding the IGNORE_DUP_KEY Feature in SQL Server

    When working with databases, maintaining data integrity is critical. SQL Server offers various tools to ensure this…

  • C# Discriminated Unions (Dunet)

    C# Discriminated Unions (Dunet)

    Dunet is a simple source generator for discriminated unions in C#. This is the nuget of this library: https://www.

  • New keyed service dependency in .NET 8

    New keyed service dependency in .NET 8

    What’s a keyed service ? The "keyed" registration approach involves registering dependencies using both their type and…

  • HttpHandler

    HttpHandler

    After a long hiatus from posting articles, today I am presenting to you a great post discussing why we need to…

  • Types of Transactions in SQL Server

    Types of Transactions in SQL Server

    Transactions are like safety nets for databases in SQL Server. They help keep data safe and consistent by making sure…

  • Dependency Injection Lifetimes in .Net Core

    Dependency Injection Lifetimes in .Net Core

    There are three lifetimes available with the Microsoft Dependency Injection container: transient, singleton, and…

  • SOLID Principles

    SOLID Principles

    SOLID is an acronym for five design principles — Single Responsibility Principle (SRP), Open-Closed Principle (OCP)…

    2 条评论
  • FileZilla - The free FTP solution

    FileZilla - The free FTP solution

    FileZilla is a free, open source file transfer protocol (FTP) software tool that allows users to set up FTP servers or…

社区洞察

其他会员也浏览了