.NET Internals7h estimated

Dependency Injection in .NET

Difficulty
Importance

The problem

A class that directly creates the concrete objects it depends on is locked to those specific implementations, making it hard to test in isolation or swap in a different implementation later — dependency injection hands a class its dependencies from outside instead of letting it construct them itself.

Why now

SOLID's Dependency Inversion principle already established depending on abstractions instead of concrete classes as a goal; dependency injection is the concrete mechanism for actually achieving that at scale, and coupling and cohesion already gave the general vocabulary (low coupling) this pattern directly serves.

Mental model

Instead of a class saying 'give me a database connection, I'll create it myself,' dependency injection has the class declare 'I need something that implements IDatabase' and receive a concrete instance from outside — typically from a DI container that's already been configured with which concrete class to hand out for each abstraction. This is exactly the creational-pattern instinct (isolate concrete construction in one place) applied at the scale of an entire application instead of one class.

Requires

Unlocks

Used in

Projects

  • Design a service class that depends on an abstraction (interface) rather than a concrete class, register both a real and a fake implementation with a DI container, and swap between them via configuration
  • Explain the difference between singleton, scoped, and transient service lifetimes with a concrete example of when each is appropriate in a web application

Examples

  • A controller depending on IEmailService rather than a concrete SmtpEmailService can be tested with a fake email service that just records calls, without ever sending a real email
  • A scoped service lifetime in ASP.NET Core creates one instance per HTTP request — appropriate for something like a database context that shouldn't be shared across unrelated requests

Resources

Mastery checklist