
Research
Security News
The Growing Risk of Malicious Browser Extensions
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
TypeDI is a dependency injection tool for TypeScript and JavaScript. It allows you to manage the lifecycle and dependencies of your services and components in a clean and efficient way.
Service Decorator
The `@Service` decorator is used to mark a class as a service that can be injected. The `Container.get` method is then used to retrieve an instance of the service.
```typescript
import { Service } from 'typedi';
@Service()
class ExampleService {
sayHello() {
return 'Hello, World!';
}
}
const exampleService = Container.get(ExampleService);
console.log(exampleService.sayHello()); // Output: Hello, World!
```
Inject Decorator
The `@Inject` decorator is used to inject a dependency into a class. In this example, `DependencyService` is injected into `MainService`.
```typescript
import { Service, Inject } from 'typedi';
@Service()
class DependencyService {
getValue() {
return 'Dependency Value';
}
}
@Service()
class MainService {
constructor(@Inject(() => DependencyService) private dependencyService: DependencyService) {}
getValue() {
return this.dependencyService.getValue();
}
}
const mainService = Container.get(MainService);
console.log(mainService.getValue()); // Output: Dependency Value
```
Container
The `Container` class is used to manage the lifecycle of services. You can manually set and get instances of services using `Container.set` and `Container.get`.
```typescript
import { Container } from 'typedi';
class ExampleService {
sayHello() {
return 'Hello, World!';
}
}
Container.set(ExampleService, new ExampleService());
const exampleService = Container.get(ExampleService);
console.log(exampleService.sayHello()); // Output: Hello, World!
```
Inversify is a powerful and flexible inversion of control (IoC) container for JavaScript and TypeScript. It provides a similar feature set to TypeDI, including decorators for services and dependency injection. Inversify is known for its extensive documentation and strong community support.
TSyringe is a lightweight dependency injection container for TypeScript. It offers a similar decorator-based API for defining and injecting services. TSyringe is designed to be simple and easy to use, making it a good choice for smaller projects or those new to dependency injection.
Awilix is a dependency injection container for JavaScript and TypeScript that focuses on developer experience and ease of use. It provides a fluent API for defining and resolving dependencies, and supports both class-based and function-based services. Awilix is known for its flexibility and ease of integration with various frameworks.
TypeDI is a dependency injection tool for TypeScript and JavaScript. With it you can build well-structured and easily testable applications in Node or in the browser.
Main features includes:
Note: This installation guide is for usage with TypeScript, if you wish to use TypeDI without Typescript please read the documentation about how get started.
To start using TypeDI install the required packages via NPM:
npm install typedi reflect-metadata
Import the reflect-metadata
package at the first line of your application:
import 'reflect-metadata';
// Your other imports and initialization code
// comes here after you imported the reflect-metadata package!
As a last step, you need to enable emitting decorator metadata in your Typescript config. Add these two lines to your tsconfig.json
file under the compilerOptions
key:
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
Now you are ready to use TypeDI with Typescript!
import { Container, Service } from 'typedi';
@Service()
class ExampleInjectedService {
printMessage() {
console.log('I am alive!');
}
}
@Service()
class ExampleService {
constructor(
// because we annotated ExampleInjectedService with the @Service()
// decorator TypeDI will automatically inject an instance of
// ExampleInjectedService here when the ExampleService class is requested
// from TypeDI.
private injectedService: ExampleInjectedService
) {}
}
const serviceInstance = Container.get(ExampleService);
// we request an instance of ExampleService from TypeDI
serviceInstance.injectedService.printMessage();
// logs "I am alive!" to the console
The detailed usage guide and API documentation for the project can be found:
./docs
folder of the repositoryPlease read our contributing guidelines to get started.
0.10.0 [BREAKING] - 2021.01.15
The Container.remove
method from now accepts one ID or an array of IDs.
// Old format
Container.remove(myServiceA, myServiceB);
// New format
Container.remove([myServiceA, myServiceB]);
Service([depA, depB], factory)
This was an undocumented way of calling the Service
function directly instead of using it as a decorator. This option
has been removed and the official supported way of achieving the same is with Container.set
. Example:
const myToken = new Token('myToken');
Container.set(myToken, 'test-value');
// Old format:
const oldWayService = Service([myToken], function myFactory(myToken) {
return myToken.toUpperCase();
});
const oldResult = Container.get(oldWayService);
// New format
const newWayService = Container.set({
// ID can be anything, we use string for simplicity
id: 'my-custom-service',
factory: function myFactory(container) {
return container.get(myToken).toUppserCase();
},
});
const newResult = Container.get('my-custom-service');
oldResult === newResult; // -> true, both equals to "TEST-VALUE"
eager
option to ServiceOptions
, when enabled the class will be instantiated as soon as it's registered in the containerdestroy
property it will be called by TypeDI@Service
decorator directlyMissingProvidedServiceTypeError
to CannotInstantiateValueError
FAQs
Dependency injection for TypeScript.
The npm package typedi receives a total of 290,812 weekly downloads. As such, typedi popularity was classified as popular.
We found that typedi demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers 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.
Research
Security News
Socket researchers uncover how browser extensions in trusted stores are used to hijack sessions, redirect traffic, and manipulate user behavior.
Research
Security News
An in-depth analysis of credential stealers, crypto drainers, cryptojackers, and clipboard hijackers abusing open source package registries to compromise Web3 development environments.
Security News
pnpm 10.12.1 introduces a global virtual store for faster installs and new options for managing dependencies with version catalogs.