DI module for Ts.ED Framework
npm install @tsed/di






![]()
![]()
![]()
![]()
![]()
![]()
A powerful and flexible Dependency Injection (DI) toolkit inspired by Angular, designed for both TypeScript and pure
JavaScript applications. Use it standalone or as the foundation of Ts.ED. Supports both decorator-based and functional (
decorator-less) APIs for maximum compatibility, even in non-TypeScript or pure JS projects.
---
Install the latest release and required peer dependencies:
``bash`
npm install --save @tsed/di @tsed/core @tsed/hooks @tsed/logger
> Important!
>
> - @tsed/di v8+ supports only ESM (ECMAScript Modules).
> - Requires Node >= 20,
> - TypeScript >= 5.0 if you use decorators.
> - For TypeScript, enable emitDecoratorMetadata and experimentalDecorators in your tsconfig.json.
---
- Providers: Register and manage services, factories, values, interceptors,
and more.
- Functional API: Register providers and factories without
decorators (for pure JS or decorator-less code).
- Async Factories: Create providers that
resolve asynchronously (e.g., database connections).
- Constants Injection: Use @Constant() or constant() to inject@Value()
configuration or static values.
- Value Injection: Use or refValue() to inject$onInit
resolved provider values.
- InjectContext: Access the injection context and advanced DI
features.
- Config Sources: Load and merge configuration
from multiple sources (files, env, remote, etc.).
- Lifecycle hooks: Manage provider lifecycle with hooks like ,$onDestroy
.inject()
- Lazy loading: Lazily load Node.js ESM modules. The lazy
loading feature allows you to declare a provider that is only instantiated when it is first injected. The DI system
will dynamically import the ESM module, discover injectable services within it, and instantiate them on
demand—enabling efficient code splitting and reducing startup time.
- Full TypeScript support: Type inference with and advanced tooling for type-safe DI.
---
Declare injectable services:
`typescript
import {Injectable} from "@tsed/di";
@Injectable()
export class UserRepository {
getUsers() {
return [{id: 1, name: "Alice"}];
}
}
@Injectable()
export class UserService {
constructor(private repo: UserRepository) {}
listUsers() {
return this.repo.getUsers();
}
}
`
Use the dependency injector:
`typescript
import {inject} from "@tsed/di";
import {UserService} from "./UserService.js";
const userService = inject(UserService);
console.log(userService.listUsers());
`
---
@tsed/di is completely standalone.
You can use it in any JS/TS project (web, CLI, backend, etc) without Ts.ED.
---
This is the recommended and most stable way to initialize and use the injector, especially when working with advanced
scenarios (settings, async providers, custom loggers, etc):
`typescript
import {injector, attachLogger, inject} from "@tsed/di";
import {$log} from "@tsed/logger";
import {CalendarCtrl} from "./CalendarCtrl.js";
// Create a new InjectorService instance
const inj = injector();
inj.settings.set(settings);
// Attach a custom logger (optional)
attachLogger($log); // Overriding the default logger is not recommended
// You can use @tsed/logger-connect to bind Ts.ED logger with any other logger
// If you have async providers or use the ConfigSource feature, ensure to await load()
await inj.load();
// Retrieve your controller (or any provider)
const calendarCtrl = inject(CalendarCtrl);
// Use your controller/service as needed
calendarCtrl.create({name: "My calendar"});
`
---
If you can't or don't want to use decorators (e.g. in pure JavaScript), use the Functional API introduced in v8+.
For exemple, we can register a provider like this:
`js
import {injectable, inject} from "@tsed/di";
// Define a class as injectable
export class UserRepository {
getUsers() {
return [{id: 1, name: "Alice"}];
}
}
injectable(UserRepository);
`
Then, you can use the inject() function to retrieve the instance of the class or any other provider:
`js
import {injectable, inject} from "@tsed/di";
// Define a factory function
export const GET_ALLOWED_USERS = injectable(Symbol.for("GET_ALLOWED_USERS"))
.factory(() => {
const userRepository = inject(UserRepository);
/// do something with userRepository
const users = userRepository.getAll();
const allowedRoles = constant("allowedRoles");
return userRepository.getUsers().filter((user) => allowedRoles.includes(user.role));
})
.token();
`
After that, we have to initialize the injector and load all providers:
`js
import {injector, attachLogger, inject} from "@tsed/di";
import {$log} from "@tsed/logger";
import "./services/GetAllowerUsers.js"; // just add import is enough to discover the providers
// Create a new InjectorService instance
const inj = injector();
inj.settings.set(settings);
// Attach a custom logger (optional)
attachLogger($log); // Overriding the default logger is not recommended
// You can use @tsed/logger-connect to bind Ts.ED logger with any other logger
// If you have async providers or use the ConfigSource feature, ensure to await load()
await inj.load();
`
The example above is the main point to start the DI system. It should be placed in the main entry file of your
application.
Now, you can use the inject() function to retrieve the instance of the class, injectable provider, or pure JavaScript
function.
For example, if you want to use the GET_ALLOWED_USERS factory in your application, you can do it like this:
`js
import {injectable, inject} from "@tsed/di";
import {GET_ALLOWED_USERS} from "./services/GetAllowerUsers.js";
// use any framework you want like express.js, hapi.js, etc.
app.get("/", async (req, res) => {
const getAllowedUser = inject(GET_ALLOWED_USERS);
const users = await getAllowedUser();
res.json(users);
});
`
Here we use the inject() function in a pure JavaScript function to retrieve the GET_ALLOWED_USERS factory.
This factory will be executed when the route is called, and it will return the allowed users.
In summary:
- No decorators required.
- Use injectable() to register functions or classes as providers.factory()
- Use or asyncFactory() to register (async) factories for advanced usage or for custom tokens.registerProvider
- Prefer this approach over in v8+.
---
You can register async factories to provide values/services that require asynchronous initialization (e.g., database
connections):
`typescript
import {injectable, inject} from "@tsed/di";
const DATABASE = injectable(Symbol.for("DATABASE"))
.asyncFactory(async () => {
const db = await connectToDatabase(); // your async init logic
return db;
})
.token();
const db = await inject(DATABASE); // Await the async factory
db.query("SELECT * FROM users");
`
- Use .asyncFactory() for asynchronous initialization.
- When injecting, await the result if the provider is async.
---
and @Value()You can inject constant values or configuration using the @Constant() decorator (or constant() function in the
Functional API):
`typescript
import {Injectable, Constant} from "@tsed/di";
@Injectable()
export class MyService {
@Constant("app.token") private token: string;
printToken() {
console.log(this.token); // Value from config
}
}
`
You can also use @Value() to inject the resolved value of a provider (by token), or refValue() for the functional
API:
`typescript
import {Injectable, Value} from "@tsed/di";
@Injectable()
export class MyService {
@Value("MY_TOKEN") private value: string;
printValue() {
console.log(this.value); // Value from MY_TOKEN provider
}
}
`
Functional API for constants and values:
`js
import {constant, refValue, inject} from "@tsed/di";
const appToken = constant("app.token", "my-api-token"); // frozen value
const refAppToken = refValue(); // reference to the app.token value. not frozen
`
- Use @Constant()/constant() for static configuration values.@Value()
- Use /refValue() for dynamic values.
Learn more: Constants and Value Injection
---
@tsed/di supports multiple provider types:
- @Injectable: Basic class providers.
- @Service: Same as @Injectable, for semantic clarity.injectable()
- @Interceptor: For registering interceptors.
- Functional API: Use , .factory(), .asyncFactory(), .value() for manual/advanced registration.@Constant()
- Constants: With /constant().@Value()
- Values: With /refValue().
- Scoped providers: Support for singleton, request, and custom scopes.
---
The DIConfiguration class provides a decorate method that allows you to extend its functionality by adding new methods or properties. You can access this method through the configuration() function.
`typescript
import {configuration} from "@tsed/di";
// Add a custom method to DIConfiguration
configuration().decorate("myCustomMethod", function () {
// Your custom logic here
return "Custom result";
});
// Usage
const result = configuration().myCustomMethod(); // "Custom result"
`
You can also add a property with a custom getter/setter:
`typescript`
configuration().decorate("customProperty", {
get() {
return this.get("someInternalValue");
},
set(value) {
this.set("someInternalValue", value);
}
});
This is particularly useful for plugin authors who want to extend the configuration capabilities without modifying the core code.
---
The $alterConfig:propertyKey hook allows you to intercept and modify configuration values before they are assigned to a property. This is useful when you need to transform, validate, or augment configuration values dynamically.
When a value is set in the configuration using the set() method, the DIConfiguration class internally calls the $alter hook with the pattern $alterConfig:${propertyKey}, passing the value as the second argument.
Here's how to use this hook:
`typescript
import {$on} from "@tsed/hooks";
// Register a hook to intercept and modify the 'jsonMapper' configuration
$on("$alterConfig:jsonMapper", (options) => {
// Modify the options before they are assigned
options.strictGroups = Boolean(options.strictGroups);
options.disableUnsecureConstructor = Boolean(options.disableUnsecureConstructor);
options.additionalProperties = Boolean(
isBoolean(options.additionalProperties) ? options.additionalProperties : options.additionalProperties === "accept"
);
// Return the modified options
return options;
});
`
This hook is particularly useful for:
- Normalizing configuration values
- Applying default values
- Validating configuration before it's applied
- Transforming configuration formats
- Implementing cross-cutting concerns for configuration properties
The hook is executed whenever the corresponding property is set, whether through direct assignment or through the configuration().set()` method.
---
- Providers
- Custom Providers
- Constants & Value Injection
- Config Sources
- Functional API
- InjectContext
---
Thank you to all our backers! 🙏 [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your
website. [Become a sponsor]
The MIT License (MIT)
Copyright (c) 2016 - 2022 Romain Lenzotti
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.