Member-only story
You are Simply Injecting a Dependency, Thinking that You are Following the Dependency Inversion Principle
Clarifying the differences.
Both the dependency inversion principle and dependency injection are completely different things, despite the similarity of the names of the terms. Understanding the differences is important for software engineers doing object-oriented programming.
Only very simple or a few low-level objects can independently implement all the functionality they need. Typically, objects need to reuse the logic of other objects. To do this, the object can simply instantiate all the required dependencies on its own using the new
keyword:
public class OrderService
{
private OrderRepository _orderRepository = new OrderRepository(); public Order PrepareOrder(long orderId)
{
var order = _orderRepository.GetOrder(orderId);
//...
}
}
The OrderService
object can reuse the logic of the OrderRepository
object. It seems that everything is good now. Each component is responsible for its own piece of work, the components interact with each other.
However, using new
keyword creates tight coupling between the object and its dependencies. The tight coupling makes the class OrderService
unusable for code…