Skip to content
SD-31 · System design

Design a Dependency Injection Framework

Asked at Staff level45 minutes
Our answers stay hidden until you reveal them.

Design a dependency injection (IoC) framework: the library that builds an application's objects for it. A developer declares that OrderService needs a PaymentClient and a Clock, and registers which classes fill those needs and how long each object lives. At startup the framework checks the whole graph; at run time get(OrderService) returns a ready object, with everything it needs built, shared or reused as declared, and closed again in the right order when its scope ends.

It will be used by 500 services across the company. The biggest has 3,000 registered types and builds a graph of about 200 objects for every web request, at 30,000 requests a second per process on 16 cores. The hard parts are cost and correctness: resolving must cost microseconds, not milliseconds, on every request, from many threads at once; mistakes in the graph, such as a missing binding, a cycle, or a shared object holding a per-request one, must be caught before production, not on the first unlucky request; and a process must start in under 2 seconds so autoscaling and deploys stay fast.

Good questions to ask first

Decide what you would assume for each before you look at ours.

  1. 1Library or service?
  2. 2Which lifetimes?
  3. 3How are bindings declared?
  4. 4Constructor injection only?
  5. 5When must errors appear?
  6. 6Is the container changed after startup?
  7. 7Do we need interceptors (logging, transactions, metrics around methods)?
  8. 8Which platforms?

How to spend the 45 minutes

  1. 5minPart 1: Requirements: library, lifetimes, when errors appear
  2. 5minPart 2: Estimates: cost per object, locks, startup
  3. 5minPart 3: API: modules, build, get, scopes, close
  4. 15minPart 4: Architecture, stage by stage
  5. 15minPart 5: Captive dependencies, thread safety, validation, codegen
Sketch your own design: boxes, arrows and the numbers that matter. Then compare it with ours.Break it in the labVisual walkthrough