Dependency Injection
· Dependency Injection (DI) is a design pattern that implements inversion of control principle for resolving dependencies.
· Instead of hardcoding dependencies within a class, dependencies are “injected” into the class from the outside
· There are three type of Injection
1. Constructor Injection : One of the most common approaches to dependency injection in C# is constructor injection. In this approach, dependencies are provided through a class’s constructor.
public class EmployeeService
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeService (IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
}
Here, the EmployeeService class depends on an interface IEmployeeRepository. The dependency is injected through the constructor, allowing different implementations of IEmployeeRepository to be supplied.
2. Property Injection : Another approach is property injection, where dependencies are exposed as public properties and are set externally. While this approach offers flexibility, it may make it less clear what dependencies a class requires.
public class EmployeeService
{
public IEmployeeRepository employeeRepository { get; set; }
}
3. Method Injection : Method injection involves passing dependencies through methods instead of constructors or properties. This approach is useful when a dependency is required for a specific method but not for the entire lifetime of the object.
Public class EmployeeService
{
public void SetEmployeeRepository(IEmployeeRepository employeeRepository)
{
_ employeeRepository = employeeRepository;
}
}
· The Benefits of Dependency Injection
1. Loose Coupling: Dependency injection promotes loose coupling by removing the direct dependencies between classes.
2. Testability: Injecting mock or test implementations of dependencies, developers can isolate the component under test, making it easier to verify its behavior without external dependencies.
3. Reusability: Dependency injection promotes code reuse.
Dependency injection is a powerful technique that promotes loosely coupled, maintainable, and testable code. By applying dependency injection principles in your C# projects, you can achieve better modularity, reusability, and flexibility.
Leave a Reply
Want to join the discussion?Feel free to contribute!