Gathering detailed insights and metrics for @tsed/di
Gathering detailed insights and metrics for @tsed/di
Gathering detailed insights and metrics for @tsed/di
Gathering detailed insights and metrics for @tsed/di
📐 Ts.ED is a Node.js and TypeScript framework on top of Express to write your application with TypeScript (or ES6). It provides a lot of decorators and guideline to make your code more readable and less error-prone. ⭐️ Star to support our work!
npm install @tsed/di
Typescript
Module System
Node Version
NPM Version
TypeScript (97.83%)
JavaScript (1.3%)
EJS (0.69%)
HTML (0.1%)
CSS (0.08%)
Shell (0.01%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
2,988 Stars
5,875 Commits
294 Forks
42 Watchers
43 Branches
145 Contributors
Updated on Jul 13, 2025
Latest Version
8.13.4
Package Id
@tsed/di@8.13.4
Unpacked Size
153.71 kB
Size
39.61 kB
File Count
156
NPM Version
10.8.2
Node Version
20.19.3
Published on
Jul 12, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
3
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:
1npm 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
andexperimentalDecorators
in 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:
1import {Injectable} from "@tsed/di"; 2 3@Injectable() 4export class UserRepository { 5 getUsers() { 6 return [{id: 1, name: "Alice"}]; 7 } 8} 9 10@Injectable() 11export class UserService { 12 constructor(private repo: UserRepository) {} 13 14 listUsers() { 15 return this.repo.getUsers(); 16 } 17}
Use the dependency injector:
1import {inject} from "@tsed/di"; 2import {UserService} from "./UserService.js"; 3 4const userService = inject(UserService); 5 6console.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):
1import {injector, attachLogger, inject} from "@tsed/di"; 2import {$log} from "@tsed/logger"; 3import {CalendarCtrl} from "./CalendarCtrl.js"; 4 5// Create a new InjectorService instance 6const inj = injector(); 7 8// Register your configuration provider 9inj.addProvider(PlatformConfiguration); 10 11// Optionally invoke and set configuration 12inj.settings = inj.invoke(PlatformConfiguration); 13inj.settings.set(settings); 14 15// Attach a custom logger (optional) 16attachLogger($log); // Overriding the default logger is not recommended 17// You can use @tsed/logger-connect to bind Ts.ED logger with any other logger 18 19// If you have async providers or use the ConfigSource feature, ensure to await load() 20await inj.load(); 21 22// Retrieve your controller (or any provider) 23const calendarCtrl = inject(CalendarCtrl); 24 25// Use your controller/service as needed 26calendarCtrl.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:
1import {injectable, inject} from "@tsed/di"; 2 3// Define a class as injectable 4export class UserRepository { 5 getUsers() { 6 return [{id: 1, name: "Alice"}]; 7 } 8} 9 10injectable(UserRepository);
Then, you can use the inject()
function to retrieve the instance of the class or any other provider:
1import {injectable, inject} from "@tsed/di"; 2 3// Define a factory function 4export const GET_ALLOWED_USERS = injectable(Symbol.for("GET_ALLOWED_USERS")) 5 .factory(() => { 6 const userRepository = inject(UserRepository); 7 /// do something with userRepository 8 const users = userRepository.getAll(); 9 const allowedRoles = constant("allowedRoles"); 10 11 return userRepository.getUsers().filter((user) => allowedRoles.includes(user.role)); 12 }) 13 .token();
After that, we have to initialize the injector and load all providers:
1import {injector, attachLogger, inject} from "@tsed/di"; 2import {$log} from "@tsed/logger"; 3import "./services/GetAllowerUsers.js"; // just add import is enough to discover the providers 4 5// Create a new InjectorService instance 6const inj = injector(); 7 8// Register your configuration provider 9inj.addProvider(PlatformConfiguration); 10 11// Optionally invoke and set configuration 12inj.settings = inj.invoke(PlatformConfiguration); 13inj.settings.set(settings); 14 15// Attach a custom logger (optional) 16attachLogger($log); // Overriding the default logger is not recommended 17// You can use @tsed/logger-connect to bind Ts.ED logger with any other logger 18 19// If you have async providers or use the ConfigSource feature, ensure to await load() 20await 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:
1import {injectable, inject} from "@tsed/di"; 2import {GET_ALLOWED_USERS} from "./services/GetAllowerUsers.js"; 3 4// use any framework you want like express.js, hapi.js, etc. 5app.get("/", async (req, res) => { 6 const getAllowedUser = inject(GET_ALLOWED_USERS); 7 const users = await getAllowedUser(); 8 9 res.json(users); 10});
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):
1import {injectable, inject} from "@tsed/di"; 2 3const DATABASE = injectable(Symbol.for("DATABASE")) 4 .asyncFactory(async () => { 5 const db = await connectToDatabase(); // your async init logic 6 return db; 7 }) 8 .token(); 9 10const db = await inject(DATABASE); // Await the async factory 11db.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):
1import {Injectable, Constant} from "@tsed/di"; 2 3@Injectable() 4export class MyService { 5 @Constant("app.token") private token: string; 6 7 printToken() { 8 console.log(this.token); // Value from config 9 } 10}
You can also use @Value()
to inject the resolved value of a provider (by token), or refValue()
for the functional API:
1import {Injectable, Value} from "@tsed/di"; 2 3@Injectable() 4export class MyService { 5 @Value("MY_TOKEN") private value: string; 6 7 printValue() { 8 console.log(this.value); // Value from MY_TOKEN provider 9 } 10}
Functional API for constants and values:
1import {constant, refValue, inject} from "@tsed/di"; 2 3const appToken = constant("app.token", "my-api-token"); // frozen value 4const 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()
.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.
No vulnerabilities found.
Reason
30 commit(s) and 20 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
no binaries found in the repo
Reason
SAST tool is run on all commits
Details
Reason
Found 2/15 approved changesets -- score normalized to 1
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
security policy file not detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
98 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More