How to Implement Dependency Injection Without a Framework
Do dependency injection without a framework in TypeScript using constructor parameters, factories and one composition root, with request scopes and tests.

You can do dependency injection in JavaScript and TypeScript with nothing but functions, constructor parameters and one file that wires everything together. No container, no decorators and no reflection are needed, and for most applications the result is easier to read and debug than a framework-driven setup. This post is a step-by-step guide on Node.js 24 and TypeScript 5.9: identify dependencies, take them as parameters, build everything in a composition root, handle per-request objects, swap implementations in tests and keep the wiring maintainable as the application grows. Each step has code and its output.
Step 1: find the hidden dependencies
Start with code that creates or imports its collaborators directly.
import { sendMail } from "./mail.ts";
import { db } from "./db.ts";
export async function registerUser(name: string, email: string) {
const id = await db.insert("users", { name, email });
await sendMail(email, `Welcome, ${name}`);
console.log(`registered user ${id}`);
return id;
}This function depends on three things beyond its arguments: the database, the mailer and the console. They are hidden in the imports. To test it you must patch modules or run a real database, and to use another mailer you must edit the function. List every such dependency: anything that does I/O, reads the clock or the environment, or that you might want to replace.
Step 2: take them as parameters
Turn each dependency into a parameter. For a function, that can be an object passed first.
interface Users {
insert(user: { name: string; email: string }): Promise<number>;
}
interface Mailer {
send(to: string, text: string): Promise<void>;
}
interface Logger {
info(message: string): void;
}
interface Deps {
users: Users;
mailer: Mailer;
logger: Logger;
}
export function makeRegisterUser({ users, mailer, logger }: Deps) {
return async function registerUser(name: string, email: string): Promise<number> {
const id = await users.insert({ name, email });
await mailer.send(email, `Welcome, ${name}`);
logger.info(`registered user ${id}`);
return id;
};
}The interfaces describe what the function needs, and nothing about how it is provided. makeRegisterUser is a factory: it takes the dependencies once and returns the function that does the work, with the dependencies captured in a closure. Nothing here imports a database or a mail library.
Try it with plain fakes.
import { makeRegisterUser } from "./after.ts";
const sent: string[] = [];
const registerUser = makeRegisterUser({
users: { insert: async () => 42 },
mailer: { send: async (to, text) => void sent.push(`${to}: ${text}`) },
logger: { info: (message) => console.log(message) },
});
console.log(await registerUser("Ada", "[email protected]"));
console.log(sent);registered user 42
42
[ '[email protected]: Welcome, Ada' ]The fakes are object literals. The logger line prints first because it runs inside the function, before the function returns the id that the outer console.log prints. No test framework or mocking library was needed.
Step 3: use classes when state belongs together
When a unit has several methods that share dependencies, a class with constructor injection reads naturally.
export class UserService {
constructor(
private readonly users: Users,
private readonly mailer: Mailer,
private readonly logger: Logger,
) {}
async register(name: string, email: string): Promise<number> {
const id = await this.users.insert({ name, email });
await this.mailer.send(email, `Welcome, ${name}`);
this.logger.info(`registered user ${id}`);
return id;
}
async invite(email: string): Promise<void> {
await this.mailer.send(email, "You are invited");
}
}The private readonly parameter properties declare and assign the fields in one step. Because Node.js 24 can run TypeScript by stripping types, note that parameter properties are not erasable syntax: running a .ts file with the default type stripping rejects them. Either enable --experimental-transform-types or use a build step, or write the fields out by hand. Choosing functions or classes is a matter of taste, and the injection technique is identical.
Step 4: wire everything in one composition root
Someone must create the real objects and connect them. Put all of that in one module, as close to the program's entry point as you can.
import { UserService } from "./service.ts";
export interface Config {
smtpHost: string;
logPrefix: string;
}
export function createApp(config: Config) {
const logger = { info: (message: string) => console.log(`${config.logPrefix} ${message}`) };
const users = {
nextId: 1,
async insert() {
return this.nextId++;
},
};
const mailer = {
async send(to: string, text: string) {
logger.info(`mail via ${config.smtpHost} to ${to}: ${text}`);
},
};
const userService = new UserService(users, mailer, logger);
return { userService };
}
const app = createApp({ smtpHost: "smtp.example.com", logPrefix: "[app]" });
console.log(await app.userService.register("Lin", "[email protected]"));[app] mail via smtp.example.com to [email protected]: Welcome, Lin
[app] registered user 1
1This function is the only place that knows which implementations exist. Reading the configuration, creating the logger, the database client and the mailer and constructing the services happens here, in an order you can see. Dependencies must be created before the things that use them, and the order of the lines in the function is the dependency graph. If it becomes hard to read, that is feedback about the design: a service with ten dependencies probably does too much.
Pass configuration as an argument, as createApp does, and read environment variables once at the very edge, in main. A function that reads process.env deep inside is a hidden dependency on the environment.
Step 5: per-request objects
Some objects live for one request, such as the current user or a request id used by the logger. Create the long-lived services once at startup, and build request-specific ones inside the handler, passing them down explicitly.
export function createRequestHandler(logger: { info(message: string): void }) {
return function handle(requestId: string, userId: number) {
const requestLogger = {
info: (message: string) => logger.info(`[${requestId}] ${message}`),
};
const context = { userId, logger: requestLogger };
return doWork(context);
};
}
function doWork(context: { userId: number; logger: { info(message: string): void } }) {
context.logger.info(`loading user ${context.userId}`);
return context.userId * 2;
}
const handle = createRequestHandler({ info: (message) => console.log(message) });
console.log(handle("req-1", 21));
console.log(handle("req-2", 5));[req-1] loading user 21
42
[req-2] loading user 5
10Each request gets its own logger that carries its own id, built from the shared logger. This is explicit scoping: nothing is hidden in a container. For deep call chains where passing a context argument becomes tedious, AsyncLocalStorage from node:async_hooks carries a value through await boundaries, as the provider pattern post shows. A DI container's "scoped lifetime" is solving the same problem with more machinery.
Step 6: replace dependencies in tests
Tests build their own graph. Because every collaborator is an interface, a fake is a few lines, and failure cases are as easy as success.
import assert from "node:assert/strict";
import { test } from "node:test";
import { UserService } from "./service.ts";
test("registering sends a welcome mail and logs the id", async () => {
const mails: string[] = [];
const logs: string[] = [];
const service = new UserService(
{ insert: async () => 7 },
{ send: async (to, text) => void mails.push(`${to}|${text}`) },
{ info: (message) => void logs.push(message) },
);
assert.equal(await service.register("Ada", "[email protected]"), 7);
assert.deepEqual(mails, ["[email protected]|Welcome, Ada"]);
assert.deepEqual(logs, ["registered user 7"]);
});
test("a failing mailer rejects the registration", async () => {
const service = new UserService(
{ insert: async () => 1 },
{ send: async () => { throw new Error("smtp down"); } },
{ info: () => {} },
);
await assert.rejects(service.register("Ada", "[email protected]"), /smtp down/);
});✔ registering sends a welcome mail and logs the id (1.2ms)
✔ a failing mailer rejects the registration (0.3ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0No module patching and no global state. You can see everything the unit uses at the top of the test.
Keeping the root manageable
As the application grows, the composition root grows with it. A few habits keep it readable.
Split by area. A createBilling(deps) function builds the billing services, and the root calls it. Each area exposes only what others need.
Return a plain object of services. createApp returns { userService, billing }, and entry points such as the HTTP server and the job runner receive what they use.
Order by dependency. Write infrastructure first, then repositories, then services, then entry points. The file reads top to bottom as a build-up.
Avoid a service locator. Do not pass the whole app object into each service so it can pick what it needs. That hides dependencies again. Each unit should declare exactly what it requires.
Watch for circular dependencies. If service A needs B and B needs A, the root cannot build either first. Extract the shared part into a third unit, or pass a callback, and treat the cycle as a design problem.
When a container starts to make sense
Manual wiring stops being pleasant when the graph has hundreds of nodes, when many objects need per-request lifetimes managed automatically, or when plugins contribute services at run time. At that point, a library such as Awilix, tsyringe or InversifyJS automates the wiring. Adopt one when you feel that pain, not earlier. Code written with constructor injection moves to a container easily, because the classes already declare their dependencies: the container only automates the new calls you were writing by hand.
Common mistakes in hand-wired DI
Creating dependencies inside a method. A call such as new Mailer() inside register puts the hidden dependency back. If a unit needs to create something per call, inject a factory function instead, so the creation is still replaceable.
Optional dependencies with silent defaults. A constructor that falls back to a real mailer when none is passed makes tests accidentally send mail. Make dependencies required, and give tests an explicit fake.
Interfaces that mirror a library. An interface copied from a vendor SDK ties the rest of your code to that vendor's vocabulary. Describe what your code needs, such as send(to, text), and let a small adapter translate to the SDK.
Injecting values that never vary. A constant like a tax rate does not need an interface. Pass it as a number in the configuration, or import it.


