What is Dependency Injection in .NET Core?
1 Answer
Dependency Injection (DI) in .NET Core is a design pattern used to achieve loose coupling between classes by providing (injecting) the dependencies a class needs from the outside, instead of the class creating them itself.
Simple Explanation
Instead of a class doing this:
public class Car
{
private Engine _engine = new Engine(); // tightly coupled
}
With Dependency Injection, you do this:
public class Car
{
private readonly IEngine _engine;
public Car(IEngine engine) // dependency injected
{
_engine = engine;
}
}
Now the Car class does not depend on a specific Engine implementation — it just depends on an abstraction (IEngine).
Why Use Dependency Injection?
- Reduces tight coupling
- Makes code easier to test (mock dependencies)
- Improves maintainability
- Promotes clean architecture
Built-in DI in .NET Core
.NET Core has a built-in IoC (Inversion of Control) container.
You register services in Program.cs (or Startup.cs in older versions):
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IEngine, PetrolEngine>();
builder.Services.AddScoped<ICarService, CarService>();
builder.Services.AddSingleton<ILogger, Logger>();
Service Lifetimes
.NET Core supports 3 lifetimes:
- Transient → New instance every time requested
- Scoped → One instance per request
- Singleton → One instance for entire application
How It Works
- You register services in the container
- You request them via constructor injection
- The framework automatically provides the instance
Example:
public class CarService : ICarService
{
private readonly IEngine _engine;
public CarService(IEngine engine)
{
_engine = engine;
}
}
.NET Core automatically injects IEngine when creating CarService.
Types of Injection
- Constructor Injection (most common)
- Property Injection
- Method Injection
Example Use Case
Imagine:
IRepository→ Data accessIService→ Business logicController→ Uses service
Each layer receives dependencies via DI, making the app modular and testable.
In One Sentence
Dependency Injection in .NET Core is a built-in mechanism that automatically supplies objects (dependencies) to classes, promoting loose coupling and better code structure.