Introduction
We are going to discuss a few basic questions, as stated below.
- What is Property Dependency Injection in C#?
- Example using Property Dependency Injection.
- When to use Property Injection over Constructor Injection?
What is Property Dependency Injection in C#?
In property injection, we need to pass object of the dependent class through a public property of the client class. Let’s use the below example for the implementation of the Property Injection or even it is called Setter Injection as value or dependency getting set in property.
Example
namespace DependencyInjectionProperty
{
public class EmpBL
{
private IEmpDAL empDAL;
public IEmpDAL EmpDataObject
{
set
{
this.empDAL = value;
}
get
{
if (empDAL == null)
{
throw new Exception("Emp is not initialized");
}
else
{
return empDAL;
}
}
}
public List<Emp> GetAllEmps()
{
return empDAL.SelectAllEmps();
}
}
}
class Program
{
static void Main(string[] args)
{
EmpBL empBL = new EmpBL();
empBL.EmpDataObject = new EmpBL();
List<Emp> ListEmp = empBL.GetAllEmps();
foreach (Emp emp in ListEmp)
{
Console.WriteLine("ID = {0}, Name = {1}", emp.ID, emp.Name);
}
Console.ReadKey();
}
}
The Property Dependency Injection in C# does not require the constructor to be changed. The dependency objects are going to be passed through the public properties of the client class. We need to use the Property Dependency Injection when we want to create the dependency object whenever it is required.
When to use Property Dependency Injection?
This type of injection in C# rarely gets used in applications. Just take an example to understand the situation when we can use it. If we have a class with many of methods and those method do not relate or depend on each other’s objects, now, in this situation, if there is any change we need to add new methods and that method is dependant on another object. If we use dependency injection in this situation then we need to change all the existing constructor calls where we created the objects. This will be very tough task if the project is big or of enterprise level. This is the perfect situation where we can use setter or property Dependency Injection.
The Constructor Dependency Injection in C# is the most commonly-used for dependency injection. It ensures that all the dependency objects are initialized before invoking any properties of the dependency object, it always avoids the null reference exceptions which is the most common mistake or error done by the programmer.