Dependency injection is a technique where an object receives the things it depends on from the outside instead of constructing them itself. It is one way to apply the Dependency Inversion Principle: high-level code depends on abstractions, and a container supplies the concrete implementations. Without DI: public class OrderService { private readonly SqlOrderRepository _repo = new SqlOrderRepository(); // hard-wired } With DI (constructor injection): public class OrderService(IOrderRepository repo, ILogger<OrderService> logger) { public Task PlaceAsync(Order order) => repo.AddAsync(order); } builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>(); builder.Services.AddScoped<OrderService>(); When ASP.NET Core creates a controller or service, the built-in container (Microsoft.Extensions.DependencyInjection) reads the constructor, resolves each dependency and its dependencies, and manages their lifetimes (transient, scoped, singleton). Benefits: - Loose coupling: swap implementations (SQL vs in-memory, real vs fake email sender) without changing the consumer. - Testability: pass mocks or fakes in unit tests. - Central configuration of object creation and lifetimes. - Cross-cutting features such as logging, options and HttpClientFactory plug in easily. Forms of injection: constructor injection (preferred, makes dependencies explicit), method injection ([FromServices] in an action, or a parameter in minimal APIs) and property injection (not supported by the built-in container). Avoid the service-locator anti-pattern — calling serviceProvider.GetService inside business code — because it hides dependencies. A constructor with many parameters is also a sign the class has too many responsibilities.
Ravindra Wadile · · 0 likes