Dependency injection means a class declares what it needs, usually in its constructor, and the framework supplies it. ASP.NET Core has a built-in container configured in Program.cs. Registering and consuming: builder.Services.AddScoped<IInvoiceRepository, InvoiceRepository>(); builder.Services.AddTransient<IPdfRenderer, PdfRenderer>(); builder.Services.AddSingleton<ICurrencyRates, CachedCurrencyRates>(); public class InvoicesController(IInvoiceRepository invoices, IPdfRenderer pdf) : ControllerBase { [HttpGet("{id}/pdf")] public async Task<IActionResult> Download(int id) => File(pdf.Render(await invoices.GetAsync(id)), "application/pdf"); } The controller never uses "new", so in tests you can pass fakes for both dependencies. Lifetime services: - AddTransient: a fresh object each time it is injected. Lightweight, stateless helpers. - AddScoped: one object per HTTP request. Repositories and DbContext, so all work in one request shares the same database context and transaction. - AddSingleton: one object for the application's life. Thread-safe shared services such as caches or exchange-rate providers that refresh periodically. Choosing correctly matters: - A DbContext registered as singleton would be shared by concurrent requests — it is not thread-safe and its change tracker would keep growing. - A scoped service injected into a singleton becomes "captive" and effectively lives forever. - Mutable state in a singleton is shared by all users. Extra points for an interview: - Keyed services (.NET 8+) let you register several implementations and pick one by key with [FromKeyedServices("key")]. - Use the Options pattern (IOptions<T>, IOptionsSnapshot<T>, IOptionsMonitor<T>) to inject configuration; IOptionsSnapshot is scoped and IOptionsMonitor is singleton-friendly. - Enable ValidateOnBuild to find missing registrations at startup instead of at runtime.
Ravindra Wadile · · 0 likes