Tutorials Design Patterns in C#
Dependency Injection in ASP.NET Core — Complete Guide
Dependency Injection in ASP.NET Core — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 60 of 69
Dependency Injection in ASP.NET Core
GoF Core ✓ → Enterprise ✓ → Cloud & Craft
Cloud & Craft · 3 — Microservices & interviews · ~10 min · Module 7: ASP.NET Core Architecture Patterns
What is this?
ASP.NET Core’s built-in container registers lifetimes (Transient/Scoped/Singleton) and constructs controllers/services automatically.
Why should you care?
ShopNest Web APIs wire dozens of services — the framework DI is the default composition root.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
// builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();
// builder.Services.AddSingleton<IClock, SystemClock>();
// app resolves controller deps automatically
Console.WriteLine("Scoped DbContext per request");
Console.WriteLine("Singleton cache shared");
What happened?
- Scoped for DbContext/request state; Singleton for thread-safe shared services; Transient for light stateless helpers.
- Captive dependency bug: singleton holding scoped.
Practice next
- Register ShopNest repo as Scoped.
- Register clock Singleton.
- Resolve in a controller ctor.
- AddHttpClient for PaymentClient.
- Try BuildServiceProvider anti-pattern — then avoid it.
Remember
Framework DI composition root. Pick lifetimes carefully. Ctor injection.
ShopNest API DI graph
Controllers get repositories via ctor.
Outcome: Tests swap fakes with WebApplicationFactory.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!