C# › Dependency Injection & IoC Principles
What is dependency injection, and what problem does it solve compared to a class creating its own dependencies directly?
BeginnerAnswer
Dependency injection means a class RECEIVES its dependencies (typically via constructor parameters) from an external source, rather than constructing them itself with 'new' — this decouples the class from specific implementations, making it far easier to swap implementations (like for testing) and centralizing how objects get wired together.
// Without DI: tightly coupled, hard to test
public class OrderService {
private readonly SqlDatabase _db = new SqlDatabase(); // hardcoded dependency
}
// With DI: loosely coupled, testable
public class OrderService {
private readonly IDatabase _db;
public OrderService(IDatabase db) { _db = db; } // injected
}Real-world example Making a service class testable by injecting a fake/mock database implementation instead of a real SQL connection during unit tests.