Property and Method Dependency Injection in C#

Property and Method Dependency Injection in C#

In this article, I am going to discuss how to implement Property and Method Dependency Injection in C# with Examples. This is a continuation part of our previous article, so, please read our previous article before proceeding to this article where we discussed Constructor Dependency Injection in C# with Example. We are also going to work with the same example that we created in our previous article. As part of this article, we are going to discuss the following pointers in detail.

  1. What is Property Dependency Injection in C#?
  2. Example using Property Dependency Injection.
  3. When to use Property Injection over Constructor Injection and vice versa?
  4. What is Method Dependency Injection in C#?
  5. Example using Method Dependency Injection.
  6. What are the advantages of using Dependency Injection?
Employee.cs 

In our previous article, we created the following Employee Model class which is going to be used by both Service Class (i.e. EmployeeDAL who is providing the services to be consumed by the client) and Client Class (i.e. EmployeeBL who is consuming the services provided by the EmployeeDAL class).

namespace DependencyInjectionDesignPattern
{
    //This is going to be our Model class which holds the Model data
    //This class is going to be used by both EmployeeDAL and EmployeeBL
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}
EmployeeDAL (Service Class):

In our previous article, we created the following EmployeeDAL (Service Class). Here, you can see, we have created the IEmployeeDAL interface which is implemented by the EmployeeDAL concrete class.

using System.Collections.Generic;
namespace DependencyInjectionDesignPattern
{
    //Dependency Object should be Interface-Based
    public interface IEmployeeDAL
    {
        List<Employee> SelectAllEmployees();
    }

    //This is the class that is responsible for Interacting with the Database
    //This class is going to be used by the EmpoloyeeBL class
    //That means it is going to be the Dependency Object
    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
                new Employee() { ID = 1, Name = "Pranaya", Department = "IT" },
                new Employee() { ID = 2, Name = "Kumar", Department = "HR" },
                new Employee() { ID = 3, Name = "Rout", Department = "Payroll" }
            };
            return ListEmployees;
        }
    }
}
What is Property Dependency Injection in C#?

In Property Dependency Injection, the Injector needs to Inject the Dependency Object through a public property of the client class. Let us see an example to understand how we can implement the Property or you can say Setter Dependency injection in C#. In our example, the EmployeeBL class is the Client Class. So, modify the EmployeeBL class as shown below.

using System.Collections.Generic;
namespace DependencyInjectionDesignPattern
{
    //This is the Class that is going to consume the services provided by the IEmployeeDAL Class
    //That means it is the Dependent Class which Depending on the IEmployeeDAL Class
    public class EmployeeBL
    {
        public IEmployeeDAL employeeDAL;

        //Injecting the Dependency Object using Public Property
        public IEmployeeDAL EmployeeDataObject
        {
            set
            {
                this.employeeDAL = value;
            }
        }

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

As you can see in the above code, we are injecting the dependency object through a public property i.e. EmployeeDataObject of the EmployeeBL class. As we are setting the dependency object through the setter property, we can call this Setter Dependency Injection in C#. Now, we need to use the property EmployeeDataObject in order to access the instance of IEmployeeDAL.

Changing Injector Code:

Now, we need to change the Injector Class code to Inject the Dependency Object using the Public Property of the EmployeeBL class. So, modify the Main method of the Program class as shown below to inject the object through the public property of the client class.

using System;
using System.Collections.Generic;
namespace DependencyInjectionDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an Instance of Client Class i.e. EmployeeBL 
            EmployeeBL employeeBL = new EmployeeBL();

            //Inject the Dependency Object using the Public Property of the Client Class
            employeeBL.EmployeeDataObject = new EmployeeDAL();

            List<Employee> ListEmployee = employeeBL.GetAllEmployees();
            foreach (Employee emp in ListEmployee)
            {
                Console.WriteLine($"ID = {emp.ID}, Name = {emp.Name}, Department = {emp.Department}");
            }
            Console.ReadKey();
        }
    }
}

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

What is Property Dependency Injection in C#?

Here the dependency object is passed through the public properties of the client class. We need to use the Setter or Property Dependency Injection when we want to create the dependency object as late as possible or we can say on-demand or when it is required.

When to use Property Dependency Injection over Constructor Injection and vice versa?

The Constructor Dependency Injection in C# is the standard for Dependency Injection. It ensures that all the dependency objects are initialized before we are going to invoke any methods or properties of the dependency object, as a result, it avoids the Null Reference Exception.

The Setter/Property Dependency Injection in C# is rarely used in Real-Time applications. For example, if I have a class that has several methods but those methods do not depend on any other objects. Now, I need to create a new method within the same class but that new method now depends on another object. If we use the constructor dependency injection here, then we need to change all the existing constructor calls where we created this class object. This can be a very difficult task if the project is a big one. Hence, in such scenarios, the Setter or Property Dependency Injection can be a good choice.

What is Method Dependency Injection in C#?

In Method Dependency Injection, we need to supply the dependency object through a public method of the client class. Let us see an example to understand how we can implement the Method Dependency Injection in C#. Let us modify the EmployeeBL class as shown below. Here, you can see, the GetAllEmployees method, takes one parameter of the dependency object, and using that parameter, it is invoking the service method.

using System.Collections.Generic;
namespace DependencyInjectionDesignPattern
{
    //This is the Class that is going to consume the services provided by the IEmployeeDAL Class
    //That means it is the Dependent Class which Depending on the IEmployeeDAL Class
    public class EmployeeBL
    {
        //Injecting the Dependency Object as Method Parameter
        public List<Employee> GetAllEmployees(IEmployeeDAL employeeDAL)
        {
            return employeeDAL.SelectAllEmployees();
        }
    }
}

Next, we need to change the Injector Class code to Inject the Dependency Object as a Method Parameter. So, modify the Main method of the Program class as shown below to inject the object through the method of the client class.

using System;
using System.Collections.Generic;
namespace DependencyInjectionDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an Instance of Client Class i.e. EmployeeBL 
            EmployeeBL employeeBL = new EmployeeBL();

            //Inject the Dependency Object as an Argument of the GetAllEmployees Method
            List<Employee> ListEmployee = employeeBL.GetAllEmployees(new EmployeeDAL());

            foreach (Employee emp in ListEmployee)
            {
                Console.WriteLine($"ID = {emp.ID}, Name = {emp.Name}, Department = {emp.Department}");
            }
            Console.ReadKey();
        }
    }
}

Now run the application and see the output as expected as shown below

Method Dependency Injection in C#

Note: We need to use the Method Dependency Injection in C# when the entire class does not depend on the dependency object but a single method of that class depends on the dependency object.

What are the Advantages of using Dependency Injection in C#?
  1. The Dependency Injection Design Pattern allows us to develop loosely coupled software components.
  2. Using Dependency Injection, it is very easy to swap with a different implementation of a component, as long as the new component implements the interface type.
Dependency Injection Container:

There are a lot of Dependency Injection Containers available in the market which implement the dependency injection design pattern. Some of the commonly used Dependency Injection Containers are as follows.

  1. Unity
  2. Castle Windsor
  3. StructureMap
  4. Spring.NET

In the next article, I am going to discuss how to implement Dependency Injection in ASP.NET MVC using the Unity Container. Here, in this article, I try to explain the Property and Method Dependency Injection in C# step by step with Examples. I hope you enjoy this Property and Method Dependency Injection in C# with Examples article. 

11 thoughts on “Property and Method Dependency Injection in C#”

  1. Ashish Sharma

    such a very very nice explanation . first time i saw step by step explain all the things. and its a very easy language .

Leave a Reply

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