- Get link
- X
- Other Apps
In C# is a design pattern that allows you to achieve Inversion of Control (IoC) by injecting dependencies (objects or services that a class needs) into a class from the outside, rather than letting the class create them itself.
Key Benefits of Dependency Injection:
1. Loose Coupling: Classes depend on abstractions (interfaces) instead of concrete implementations, making the code more flexible and testable.
2. Easier Testing: Dependencies can be replaced with mock or fake objects for unit testing.
3. Simplified Code Maintenance: Changing a dependency doesn't require altering the dependent class.
Example Without Dependency Injection:
public class Service {
public string GetData() => "Service Data";
}
public class Client {
private Service _service = new Service(); // Tight coupling
public string UseService() => _service.GetData();
}
Here, `Client` directly creates an instance of `Service`, which makes it hard to replace or test `Service`.
Example With Dependency Injection:
public class Service : IService {
public string GetData() => "Service Data";
}
public interface IService {
string GetData();
}
public class Client {
private readonly IService _service;
public Client(IService service) { // Dependency is injected
_service = service;
}
public string UseService() => _service.GetData();
}
Here, `Client` depends on the abstraction (`IService`), and the concrete implementation (`Service`) is injected into it.
Implementing Dependency Injection in ASP.NET Core:
ASP.NET Core has built-in support for DI through its service container.
Example:
// Registering services in the DI container
builder.Services.AddScoped<IService, Service>();
// Injecting the service into a controller
public class ClientController : ControllerBase {
private readonly IService _service;
public ClientController(IService service) {
_service = service;
}
[HttpGet]
public IActionResult Get() {
return Ok(_service.GetData());
}
}
In this approach, ASP.NET Core automatically resolves the `IService` dependency when creating `ClientController`.
Comments