Dependency Injection is a design pattern where an object receives the other objects it depends on from an external source instead of creating them itself, which makes code more testable, loosely coupled, and easier to maintain. dot NET Core has built in support for Dependency Injection through its service container, where you register your services, usually interfaces mapped to concrete classes, in the Program.cs or Startup.cs file, and the framework automatically supplies the correct instance wherever it is needed, such as inside a controller constructor.
// Registering a service
builder.Services.AddScoped<IEmailService, EmailService>();
// Consuming it in a controller
public class OrdersController {
private readonly IEmailService _emailService;
public OrdersController(IEmailService emailService) {
_emailService = emailService;
}
}
Real-world example
An e commerce API registers an IPaymentGateway interface with a specific payment provider implementation, so every controller that needs to process a payment automatically receives the correctly configured payment service without creating it manually.
What is Middleware in .NET Core? How does the request pipeline work?;What are Configuration and Options pattern in .NET Core?