Dependency Injection
The backend uses a container-based DI pattern for service wiring, testability, and loose coupling.
Container Assembly
The DI container is created in backend/src/services/create-services.ts. It assembles all services with their dependencies and exposes them through a typed container object.
Injection via Hono Context
Services are injected into Hono route handlers via context variables:
| Context Variable | Access Pattern | Contains |
|---|---|---|
c.var.services | Business services | All domain services (46) |
c.var.container | Infrastructure | infrastructure, crossCutting |
Route Access (MANDATORY)
// Always destructure directly
const { documentRequests, portal } = c.var.services;
const { infrastructure } = c.var.container;
// NEVER alias
// const svc = c.var.services.documentRequests;Interface Contracts
Each service implements an interface from backend/src/interfaces/ (48 files):
| Interface | Service |
|---|---|
buildings-service.ts | buildings-service.ts |
quote-service.ts | quote-service.ts |
contact-service.ts | contact-service.ts |
service-container.ts | Container type definition |
database-client.ts | DB connection interface |
cache-client.ts | Redis/cache interface |
storage-client.ts | File storage interface |
Infrastructure interfaces (database-client.ts, cache-client.ts, storage-client.ts, logger-factory.ts) enable swapping implementations between environments.
Testing Setup
Tests MUST set both container and services on the Hono context:
c.set('container', container);
c.set('services', container.services);Missing either will cause runtime errors in route handlers.
Benefits
- Testability — mock any service via its interface
- Reuse — services work in routes AND background job processors
- Loose coupling — services depend on interfaces, not implementations
- Single assembly point —
create-services.tsis the only place dependencies are wired
See Also
- Service Layer Pattern — how services are structured
- Backend Architecture — overall backend design
- Services Overview — complete service catalog
- Background Jobs — services reused in job processors