Member-only story
Software Architecture
What Happens Inside Your DI Container — I Built One to Find Out
Graph theory, topological sorting, and the hidden complexity behind services.AddScoped()
Anto Semeraro8 min read·1 hour ago--
Someone on the team once asked a question during a code review that I couldn’t answer properly. They pointed at our Startup.cs, sixty-something registrations deep, and said: "What actually happens when the framework resolves all of this? Like, in what order?"
I mumbled something about reflection and constructor inspection. It was mostly correct. It was also completely superficial.
That question stuck. So I did the only thing that actually works when you want to understand something: I built one.
The problem a DI container solves
Strip away the frameworks and the syntax sugar, and dependency injection solves a graph problem.
Every service in your application depends on other services. OrderService needs IOrderRepository and IPaymentGateway. IPaymentGateway needs IHttpClientFactory and ILogger<PaymentGateway>. Each dependency has its own dependencies. The whole thing forms a directed acyclic graph — or at least, it should be acyclic. When it isn't, you have a circular dependency, and…