Skip to content
SD-31 · Back to the write-up

Design a Dependency Injection Framework

Freeze the bindings, check the whole graph once, compile a plan per type, and let each request's scope build and close its own objects.

Follow a request

Caller
Run time
Build and startup
ApplicationOpens scopes, calls get
ResolverRuns plans
Singleton cacheLock-free reads
Request scopeScoped objects
LifecycleDispose in reverse
Plan compilerOne plan per type
RegistryFrozen bindings
Modulesbind(T → Impl)
ValidatorWhole graph at build
Code generatorCompile time
ReflectionDev mode only
1app → scope · open scopeThe web framework opens a request scope: one small, empty map.1 / 7

The numbers, at a glance

Container CPU per requestMicroseconds, 200 objects or 30 with singletons
The container's share of a requestCompiled plans and singletons
With reflection on every resolve it would be 90%.
Startup for 3,000 typesSeconds

A request, in order

Singletons were built at startup; only the request's scoped objects are new.

Web framework
Request scope
Resolver
Plan cache
Singleton cache
Lifecycle
1 open scope
2 get(OrderHandler)
3 plan #812
4 steps
5 read 4 slots
6 instances
7 store 3 scoped
8 OrderHandler
9 close scope
10 dispose in reverse
RequestResponseAsync, does not block

When the container learns the graph

The decision this question is really about.

Reflect per resolve
Too slow
get(T)
reflect ×200
3 ms a request
+ No build step.− 15 µs per object, errors at run time.
Plan once per type
Good default
first get(T)
reflect once → plan
5.5 s startup
+ 1 µs per object.− Startup still scans every class.
Generate at compile
Our pick
compile
validate + write factories
0.3 s startup
+ No reflection, errors fail the build.− A build step to maintain.

How it grows

Add a box only when a number forces you to. Highlighted boxes are new at each stage.

Stage 1 · ≈ 500 requests/sMake it work
Application
ResolverReflection
RegistryModules
A registry and a resolver that reflects on every call.
Stage 2 · ≈ 2,000 requests/sLifetimes and scopes
Application
ResolverReflection
Singleton cacheRequest scopesLifecycle
RegistryModules
Singletons built once, request scopes, disposal in reverse.
Stage 3 · ≈ 30,000 requests/sCompile and validate
Application
ResolverPlan compiler
Singleton cache, lock-freeRequest scopesLifecycle
RegistryModulesValidator
Plans per type, lock-free singleton reads, graph checks at startup.
Stage 4 · 30,000 requests/s, 0.3 s startBuild time
Application
ResolverPlan compiler
Singleton cache, lock-freeRequest scopesLifecycle
RegistryModulesValidatorCode generator
Generate factories and validate at compile time.
Was this walkthrough useful?Your vote tells us what to improve next.