Dependency Injection (DI) is a design pattern in which an object's dependencies are provided from outside rather than created inside the object. It implements Inversion of Control: the object no longer controls how its collaborators are built. Why it exists — consider tight coupling: public class NotificationService { private readonly SmtpEmailSender _sender = new(); // cannot change or test } With DI: public interface IEmailSender { Task SendAsync(string to, string body); } public class NotificationService(IEmailSender sender) { public Task WelcomeAsync(User u) => sender.SendAsync(u.Email, "Welcome!"); } builder.Services.AddScoped<IEmailSender, SmtpEmailSender>(); Now production uses SMTP, tests pass a fake sender, and switching to SendGrid means changing one registration. Three types of injection: - Constructor injection — the standard approach; dependencies are required and visible. - Method (parameter) injection — for example [FromServices] on an action or parameters in minimal API handlers. - Property injection — supported by some third-party containers (Autofac), not by the built-in one. What the container does: - Builds the object graph automatically, recursively resolving constructor parameters. - Manages lifetimes: transient, scoped (per request) and singleton. - Disposes IDisposable services at the end of their lifetime. Benefits: loose coupling, easier unit testing, single place to configure implementations, and support for cross-cutting features like logging and configuration. Pitfalls: overusing interfaces for classes that will only ever have one implementation, constructors with too many dependencies (a design smell), the service-locator anti-pattern (asking IServiceProvider for services inside business logic), and lifetime mismatches such as scoped-in-singleton.
Ravindra Wadile · · 0 likes