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
Build the container
Serve a request
First resolve in dev mode
Catch a captive dependency
A constructor throws
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
The numbers, at a glance
3,000 µsReflect, all new
450 µsReflect, singletons
200 µsPlans, all new
30 µsPlans, singletons
9% container91% application work
5.5 sScan + validate
4 sScan only
0.3 sGenerated code
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.
get(T)
reflect ×200
3 ms a request
+ No build step.− 15 µs per object, errors at run time.
first get(T)
reflect once → plan
5.5 s startup
+ 1 µs per object.− Startup still scans every class.
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.
Application
ResolverReflection
RegistryModules
Application
ResolverReflection
Singleton cacheRequest scopesLifecycle
RegistryModules
Application
ResolverPlan compiler
Singleton cache, lock-freeRequest scopesLifecycle
RegistryModulesValidator
Application
ResolverPlan compiler
Singleton cache, lock-freeRequest scopesLifecycle
RegistryModulesValidatorCode generator
Was this walkthrough useful?Your vote tells us what to improve next.