Microsoft Solutions
Backend Development
AI Consulting
E-Commerce Apps
Frontend Development
Cloud Solutions
Frontend
Backend
Mobile App
Microsoft
Industry we Served
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
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.
public class EmployeeService
{
public IEmployeeRepository employeeRepository { get; set; }
}
Public class EmployeeService
{
public void SetEmployeeRepository(IEmployeeRepository employeeRepository)
{
_ employeeRepository = employeeRepository;
}
}
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.