Medium15 minDesign Patterns

Dependency Injection

Dependency Injection (DI)

Why This Is Asked

DI is a foundational pattern in modern software. Interviewers want to confirm you understand Inversion of Control, can explain the benefits of loose coupling and testability, and know how DI containers manage object lifetimes.

Key Concepts

  • Dependency Injection is a form of Inversion of Control (IoC) where dependencies are provided externally
  • Three injection styles: constructor injection (most common), method injection, property injection
  • Service lifetimes: Transient (new instance per request), Scoped (per scope/HTTP request), Singleton (shared)
  • Enables unit testing by allowing mock/stub substitution
  • The composition root is where the entire object graph is wired up

Answers by Technology

+ Add Variant
.NETImprove this answer ✏️

Expected Answer (.NET)

ASP.NET Core provides a native DI container. The three service lifetimes are:

  1. Transient: Created every time they are requested.
  2. Scoped: Created once per client request (within a scope).
  3. Singleton: Created once the first time they are requested.

Common Mistakes

  • Injecting a Scoped service into a Singleton.
  • Manual instantiation of classes that should be managed by the DI container.

Follow-up Questions

  • What is the IServiceCollection?
  • How do you resolve a service manually using IServiceProvider?