
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
@tsed/di
Advanced tools






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:
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
emitDecoratorMetadataandexperimentalDecoratorsin yourtsconfig.json.
@Constant() or constant() to inject
configuration or static values.@Value() or refValue() to inject
resolved provider values.$onInit,
$onDestroy.inject() and advanced tooling for type-safe DI.Declare injectable services:
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:
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):
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:
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:
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:
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:
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:
injectable() to register functions or classes as providers.factory() or asyncFactory() to register (async) factories for advanced usage or for custom tokens.registerProvider in v8+.You can register async factories to provide values/services that require asynchronous initialization (e.g., database connections):
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");
.asyncFactory() for asynchronous initialization.@Constant() and @Value()You can inject constant values or configuration using the @Constant() decorator (or constant() function in the
Functional API):
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:
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:
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
@Constant()/constant() for static configuration values.@Value()/refValue() for dynamic values.Learn more: Constants and Value Injection
@tsed/di supports multiple provider types:
@Injectable, for semantic clarity.injectable(), .factory(), .asyncFactory(), .value() for manual/advanced registration.@Constant()/constant().@Value()/refValue().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.
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:
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:
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:
The hook is executed whenever the corresponding property is set, whether through direct assignment or through the configuration().set() method.
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.
FAQs
DI module for Ts.ED Framework
The npm package @tsed/di receives a total of 17,348 weekly downloads. As such, @tsed/di popularity was classified as popular.
We found that @tsed/di demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.