wasAsked.

what is dependency injection?

Mphasis · Role not specified · technical

Published

Year not specified · .NET

Community answers

Posted by wasAsked editorial collection

Dependency Injection (DI) is a design pattern where a class receives the objects it depends on from an external source instead of creating them itself. It is a practical way to achieve loose coupling and the Dependency Inversion Principle. Simple analogy: a car does not build its own engine; the factory installs one. The car only needs "an engine" that meets an agreed interface. In code: public interface IPaymentGateway { Task<bool> ChargeAsync(decimal amount); } public class CheckoutService { private readonly IPaymentGateway _gateway; public CheckoutService(IPaymentGateway gateway) => _gateway = gateway; // injected public Task<bool> PayAsync(decimal amount) => _gateway.ChargeAsync(amount); } // ASP.NET Core registration builder.Services.AddScoped<IPaymentGateway, RazorpayGateway>(); builder.Services.AddScoped<CheckoutService>(); The container sees that CheckoutService needs IPaymentGateway, creates a RazorpayGateway and passes it in automatically. Why it is useful: - Testability: unit tests inject a fake gateway, so no real money moves. - Flexibility: switch to another provider by changing one registration. - Maintainability: classes have clear, explicit dependencies, and object creation is managed in one place. - Lifetime management: the container controls how long objects live (transient, scoped, singleton) and disposes them. Types of DI: - Constructor injection — the standard and recommended approach. - Method injection — dependencies passed to a method ([FromServices], minimal API parameters). - Property injection — set through properties (needs a third-party container in .NET). Watch out for: lifetime mismatches (scoped inside singleton), too many constructor parameters (a sign the class does too much), and using IServiceProvider as a service locator inside business code.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics