liveBook · Manning

Dependency injection

As explained in .NET in Action, Second Edition

Dependency injection is a pattern in which an object receives its dependencies from an external composition mechanism rather than creating them itself.

Dependency injection is a pattern in which an object receives the objects it depends on from an external composition mechanism instead of creating them itself. In ASP.NET Core, a controller can delegate dependency creation to the application handling the request. section 5.4.1

The injected object is the dependency. The application controls which implementation is supplied and can control its lifetime. This separation also makes testing easier because a controller can receive a fake context instead of constructing a real one. section 5.4.1 section 7.0

A practical ASP.NET Core arrangement has three parts:

  • Register the dependency with the application service collection, allowing the framework to provide it when constructing the controller. section 5.4.1
  • Replace production dependencies with mocks or fakes in tests when specific return values or isolated behavior are needed. section 7.0

Injecting an EF Core context

CatalogController accepts CatalogContext in its constructor and queries the stored _dbContext field. Program registration with builder.Services.AddDbContext<CatalogContext>() lets ASP.NET Core supply that dependency. A test can provide a fake context instead of allowing the controller to create one. section 5.4.1

How .NET in Action, Second Edition covers it

How deep it goes
Explains dependencies, constructor provision, lifetime control, service registration, and test substitution.
Examples
Uses CatalogController receiving CatalogContext, AddDbContext registration, and fake or mock replacements during testing.
What it assumes
Assumes familiarity with ASP.NET Core controllers and services while introducing dependencies and test substitution.
What you can do after
Apply it via ASP.NET Core service registration and constructor injection, then substitute fakes or mocks during testing.
How it connects
Connects dependency injection with inversion of control, ASP.NET Core, controllers, unit testing, mocks, fakes, and dependency inversion.

Also explained in

Compare how 21 books explain dependency injection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.