What is Dependency Injection in C# and How It Works
C# is a technique where an object receives its dependencies from an external source rather than creating them itself. This helps make code easier to manage, test, and extend by separating concerns and reducing tight coupling.How It Works
Imagine you are building a toy car, but instead of making the wheels yourself, you get them from a wheel factory. Dependency injection works similarly: instead of a class creating its own parts (dependencies), it gets them from outside. This means the class only focuses on what it needs to do, not how to create everything it uses.
In C#, this usually means passing the needed objects through a constructor, method, or property. This way, the class depends on abstractions (like interfaces) rather than concrete implementations, making it easier to swap parts without changing the class itself.
Example
This example shows a Car class that needs an IEngine. Instead of creating the engine inside, it receives it through the constructor. This is constructor injection, a common form of dependency injection.
using System; public interface IEngine { void Start(); } public class GasEngine : IEngine { public void Start() { Console.WriteLine("Gas engine started."); } } public class Car { private readonly IEngine _engine; public Car(IEngine engine) { _engine = engine; } public void Drive() { _engine.Start(); Console.WriteLine("Car is driving."); } } public class Program { public static void Main() { IEngine engine = new GasEngine(); Car car = new Car(engine); // Injecting dependency car.Drive(); } }
When to Use
Use dependency injection when you want to make your code easier to test, maintain, and extend. It is especially helpful in large projects where classes have many dependencies or when you want to swap implementations without changing the main code.
For example, in a web application, you might inject different database services or logging tools depending on the environment (development, testing, production). This makes your code flexible and reduces the chance of bugs caused by tightly coupled components.
Key Points
- Dependency injection passes dependencies from outside instead of creating them inside a class.
- It promotes loose coupling and easier testing by using interfaces or abstractions.
- Common injection methods include constructor, property, and method injection.
- It helps swap implementations without changing dependent classes.
- Widely used in modern C# applications and frameworks like ASP.NET Core.