Dependency Injection Design Pattern in C#

Dependency Injection Design Pattern in C# with Real-Time Examples

In this article, I am going to discuss the Dependency Injection Design Pattern in C# with examples. Please read our previous article where we discussed the Singleton Design Pattern in C# with some examples. Nowadays, the dependency injection design pattern is one of the most frequently used design patterns in real-time applications. So, as a developer, you should know why and how to use dependency injection design pattern. We divided the dependency injection design pattern into three parts. As part of this article, we are going to discuss the following pointers in detail.

  1. Why Do We Need Dependency Injection Design Pattern in C#?
  2. What is Tight Coupling and Loose Coupling in Software Design?
  3. What is Dependency Injection Design Pattern in C#?
  4. Types of Dependency Injection Design Pattern in C#.
          Constructor Injection
          Property Injection
          Method Injection
  5. Example using Constructor Dependency Injection
  6. What are the Advantages of Constructor Dependency Injection?

In part 2, we will discuss Property and Method Dependency Injection with examples. And in part 3, we will discuss the Unity Container in C# with an example.

Why do we need the Dependency Injection Design Pattern in C#?

The Dependency Injection is a design pattern that allows us to develop loosely coupled software components. In other words, we can say that this design pattern is used to reduce the tight coupling between the software components. As a result, we can easily manage future changes and other complexity in our application.

Before understanding the Dependency Injection Design Pattern using C#, first, we need to understand what is tight coupling and what is loose coupling in software development. So let’s understand these two concepts first.

What is Tight Coupling in Software Design?

Tight coupling means classes and objects are dependent on each other. That means when a class is dependent on another concrete class, then it is said to be a tight coupling between these two classes. In that case, if we change the dependent object, then we also need to change the classes where this dependent object is used. If your application is a small one, then it is not that difficult to handle but if you have a big enterprise-level application, then its really very difficult to handle to make these changes.

What is Loose Coupling in Software Design?

Loosely coupling means two objects are independent of each other. That means if we change one object then it will not affect another object. The loosely coupled nature of software development allows us to manage future changes easily and also allows us to manage the complexity of the application.

What is Dependency Injection Design Pattern in C#?

The Dependency Injection Design Pattern in C# is a process in which we are injecting the object of a class into a class that depends on that object. The Dependency Injection design pattern is the most commonly used design pattern nowadays to remove the dependencies between the objects.

Different Types of Dependency Injection in C#?

We can implement the Dependency Injection in C# in three different ways. They are as follows.

Constructor Injection: When we supply the dependency object through the client class constructor, then it is called as Constructor Injection.

Property Injection: When we supply the dependency object through the public property of the client class, then it is called as Property Injection.

Method Injection: When we supply the dependency object through a public method of the client class, then it is called as Method Injection.

Here, in this article, I will discuss how to inject the dependency object through the constructor. In the next article, I am going to discuss the Method and Property Dependency injection in C# with examples.

Constructor Dependency Injection in C#:

Let us understand the Constructor Dependency Injection in C# with an example. Let’s create a console application. to do so select, File => New => Project and then select the console application as shown below.

Dependency Injection Design Pattern in C#

Now create 3 classes Employee.cs, EmployeeDAL.cs and EmployeeBL.cs as shown below

Employee.cs

namespace DependencyInjectionExample
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}

EmployeeDAL.cs

namespace DependencyInjectionExample
{
    public class EmployeeDAL
    {
        public List<Employee> SelectAllEmployees()
        {
            List<Employee> ListEmployees = new List<Employee>();
            //Get the Employees from the Database
            //for now we are hard coded the employees
            ListEmployees.Add(new Employee() { ID = 1, Name = "Pranaya", Department = "IT" });
            ListEmployees.Add(new Employee() { ID = 2, Name = "Kumar", Department = "HR" });
            ListEmployees.Add(new Employee() { ID = 3, Name = "Rout", Department = "Payroll" });
            return ListEmployees;
        }
    }
}

EmployeeBL.cs

namespace DependencyInjectionExample
{
    public class EmployeeBL
    {
        public EmployeeDAL employeeDAL;

        public List<Employee> GetAllEmployees()
        {
            employeeDAL = new EmployeeDAL();
            return employeeDAL.SelectAllEmployees();
        }
    }
}

In the above example, in order to get the data, the EmployeeBL class depends on the EmployeeDAL class. In the GetAllEmployees() method of the EmployeeBL class, we create an instance of the EmployeeDAL (Employee Data Access Layer) class and then invoke the SelectAllEmployees() method. This is tight coupling because the EmployeeDAL is tightly coupled with the EmployeeBL class. Every time the EmployeeDAL class changes, the EmployeeBL class also needs to change. 

Let us see how to use the constructor injection to make these classes loosely coupled.

Modify the EmployeeDAL.cs file as shown below
namespace DependencyInjectionExample
{
    public interface IEmployeeDAL
    {
        List<Employee> SelectAllEmployees();
    }

    public class EmployeeDAL : IEmployeeDAL
    {
        public List<Employee> SelectAllEmployees()
        {
            List<Employee> ListEmployees = new List<Employee>();
            //Get the Employees from the Database
            //for now we are hard coded the employees
            ListEmployees.Add(new Employee() { ID = 1, Name = "Pranaya", Department = "IT" });
            ListEmployees.Add(new Employee() { ID = 2, Name = "Kumar", Department = "HR" });
            ListEmployees.Add(new Employee() { ID = 3, Name = "Rout", Department = "Payroll" });
            return ListEmployees;
        }
    }
}

As you can see, first we create one interface i.e IEmployeeDAL with the one method. Then that interface is implemented by the EmployeeDAL class. So the point that I need to keep focus is when you are going to use the dependency injection design pattern in c#, then the dependency object should be interface based. In our example, the EmployeeDAL is the dependency object as this object is going to be used by the EmplyeeBL class. So we created the interface and then implement that interface. 

Modify the EmployeeBL.cs file as shown below
namespace DependencyInjectionExample
{
    public class EmployeeBL
    {
        public IEmployeeDAL employeeDAL;
        public EmployeeBL(IEmployeeDAL employeeDAL)
        {
            this.employeeDAL = employeeDAL;
        }
        public List<Employee> GetAllEmployees()
        {
            Return employeeDAL.SelectAllEmployees();
        }
    }
}

In the above example, we created one constructor which accepts one parameter of the dependency object type. The point that you need to keep focus is, the parameter of the constructor is of the type interface, not the concrete class. Now, this parameter can accept any concrete class object which implements this interface.

So here in the EmployeeBL class, we are not creating the object of the EmployeeDAL class. Instead, we are passing it as a parameter to the constructor of the EmployeeBL class. As we are injecting the dependency object through the constructor, it is called as constructor dependency injection in C#.

Let’s us see how to use EmployeeBL class in our Main method of Program class:
namespace DependencyInjectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            EmployeeBL employeeBL = new EmployeeBL(new EmployeeDAL());
            List<Employee> ListEmployee = employeeBL.GetAllEmployees();
            foreach(Employee emp in ListEmployee)
            {
                Console.WriteLine("ID = {0}, Name = {1}, Department = {2}", emp.ID, emp.Name, emp.Department);
            }
            Console.ReadKey();
        }
    }
}

Now run the application and you will see the output as expected as shown below.

Dependency Injection in C#

Advantages of Constructor Dependency Injection
  1. The Constructor Dependency Injection Design Pattern makes a strong dependency contract
  2. This design pattern support testing as the dependencies are passed through the constructor.

In the next article, I am going to discuss the Property and Method dependency injection with some real-time examples. Here, in this article, I try to explain the Dependency Injection Design Pattern in C# steps by step with an example. I hope you understood the need and use of the Dependency Injection Design Pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *