DI stands for Dependency Injection. Instead of a class creating its own dependencies with "new", the dependencies are supplied ("injected") from outside — usually through the constructor — by a DI container. This keeps classes loosely coupled and easy to test. Example: public interface ISmsSender { Task SendAsync(string phone, string text); } public class OtpService(ISmsSender sms) { public Task SendOtpAsync(string phone, string code) => sms.SendAsync(phone, $"Your OTP is {code}"); } builder.Services.AddScoped<ISmsSender, TwilioSmsSender>(); builder.Services.AddScoped<OtpService>(); In tests you can pass a fake ISmsSender that records messages instead of sending them. The "various states" of DI are its service lifetimes: 1. Transient (AddTransient): a new object every time it is requested. Good for small stateless services. 2. Scoped (AddScoped): one object per HTTP request, shared by everything in that request. Good for DbContext and request-specific services. 3. Singleton (AddSingleton): one object for the whole application. Good for configuration, caching and other thread-safe shared services. Ways to inject: - Constructor injection (recommended). - Method or action injection with [FromServices], or directly as parameters in minimal API handlers. - Property injection is not supported by the built-in container (third-party containers such as Autofac support it). Common mistakes: - Injecting a scoped service into a singleton (captive dependency). - Using IServiceProvider.GetService everywhere (service locator), which hides dependencies. - Registering everything as singleton for "performance", which causes thread-safety and data-leak problems. Benefits: testability, flexibility to swap implementations, clean separation of concerns, and central management of object creation and disposal.
Ravindra Wadile · · 0 likes