Convert Figma logo to code with AI

typestack logotypedi

Simple yet powerful dependency injection tool for JavaScript and TypeScript.

4,025
168
4,025
51

Top Related Projects

A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.

66,731

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀

Lightweight dependency injection container for JavaScript/TypeScript

16,828

AdonisJS is a TypeScript-first web framework for building web apps and API servers. It comes with support for testing, modern tooling, an ecosystem of official packages, and more.

3,525

Extremely powerful Inversion of Control (IoC) container for Node.JS

Quick Overview

TypeDI is a dependency injection container for TypeScript and JavaScript applications. It provides a powerful and flexible way to manage dependencies and inversion of control, making it easier to build modular and testable applications.

Pros

  • Seamless integration with TypeScript, leveraging decorators and metadata reflection
  • Supports both constructor and property injection
  • Allows for circular dependencies and lazy-loaded services
  • Provides a clean and intuitive API for managing dependencies

Cons

  • Requires TypeScript and experimental decorators to be enabled for full functionality
  • May introduce additional complexity for smaller projects
  • Learning curve for developers new to dependency injection concepts
  • Limited documentation and examples compared to some other DI libraries

Code Examples

  1. Basic service and injection:
import { Service, Inject, Container } from 'typedi';

@Service()
class UserService {
  getUsers() {
    return ['Alice', 'Bob', 'Charlie'];
  }
}

@Service()
class UserController {
  constructor(@Inject() private userService: UserService) {}

  listUsers() {
    return this.userService.getUsers();
  }
}

const userController = Container.get(UserController);
console.log(userController.listUsers());
  1. Using factory functions:
import { Service, Container } from 'typedi';

@Service({ factory: () => new Date() })
class CurrentDate {}

@Service()
class TimeService {
  constructor(private currentDate: CurrentDate) {}

  getCurrentTime() {
    return this.currentDate.toLocaleTimeString();
  }
}

const timeService = Container.get(TimeService);
console.log(timeService.getCurrentTime());
  1. Scoped containers:
import { Container, Service, ContainerInstance } from 'typedi';

@Service()
class ScopedService {
  constructor(public container: ContainerInstance) {}
}

const container1 = Container.of('scope1');
const container2 = Container.of('scope2');

const service1 = container1.get(ScopedService);
const service2 = container2.get(ScopedService);

console.log(service1.container === container1); // true
console.log(service2.container === container2); // true

Getting Started

  1. Install TypeDI:

    npm install typedi reflect-metadata
    
  2. Enable experimental decorators and metadata in tsconfig.json:

    {
      "compilerOptions": {
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
      }
    }
    
  3. Import reflect-metadata at the top of your entry file:

    import 'reflect-metadata';
    
  4. Start using TypeDI in your application:

    import { Service, Inject, Container } from 'typedi';
    
    @Service()
    class MyService {
      doSomething() {
        return 'Hello, TypeDI!';
      }
    }
    
    @Service()
    class MyController {
      constructor(@Inject() private myService: MyService) {}
    
      greet() {
        return this.myService.doSomething();
      }
    }
    
    const controller = Container.get(MyController);
    console.log(controller.greet());
    

Competitor Comparisons

A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.

Pros of InversifyJS

  • More mature and feature-rich, with a larger ecosystem of extensions and plugins
  • Supports advanced features like tagged bindings and contextual bindings
  • Offers more flexibility in configuration and container setup

Cons of InversifyJS

  • Steeper learning curve due to its more complex API and advanced features
  • Requires more boilerplate code for basic dependency injection scenarios
  • Slightly larger bundle size compared to TypeDI

Code Comparison

TypeDI:

import { Container, Service, Inject } from 'typedi';

@Service()
class UserService {
  @Inject()
  private database: Database;
}

InversifyJS:

import { injectable, inject, Container } from 'inversify';

@injectable()
class UserService {
  constructor(@inject(Database) private database: Database) {}
}

Both TypeDI and InversifyJS are popular dependency injection containers for TypeScript. TypeDI is simpler and more straightforward, making it easier to get started with basic dependency injection. InversifyJS, on the other hand, offers more advanced features and flexibility, but comes with a steeper learning curve.

TypeDI uses decorators for both class and property injection, while InversifyJS primarily uses constructor injection. InversifyJS requires more setup code, including explicit bindings, but provides greater control over how dependencies are resolved.

Choose TypeDI for simpler projects or when getting started with dependency injection. Opt for InversifyJS when you need more advanced features or greater flexibility in your dependency injection setup.

66,731

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀

Pros of Nest

  • Full-featured framework with built-in support for various architectural patterns
  • Extensive ecosystem with official and community modules
  • Strong TypeScript integration and decorators for enhanced developer experience

Cons of Nest

  • Steeper learning curve due to its comprehensive nature
  • Potentially overkill for smaller projects or microservices
  • Opinionated structure may limit flexibility in some scenarios

Code Comparison

Nest:

@Injectable()
export class CatsService {
  private readonly cats: Cat[] = [];

  create(cat: Cat) {
    this.cats.push(cat);
  }

  findAll(): Cat[] {
    return this.cats;
  }
}

TypeDI:

@Service()
class CatsService {
  private readonly cats: Cat[] = [];

  create(cat: Cat) {
    this.cats.push(cat);
  }

  findAll(): Cat[] {
    return this.cats;
  }
}

Both frameworks use decorators for dependency injection, but Nest provides a more comprehensive set of decorators and built-in features for creating full-fledged applications. TypeDI focuses primarily on dependency injection, offering a simpler and more lightweight approach for projects that don't require the full feature set of Nest.

Lightweight dependency injection container for JavaScript/TypeScript

Pros of TSyringe

  • Developed and maintained by Microsoft, potentially offering better long-term support
  • Simpler API with fewer decorators, making it easier to learn and use
  • Supports circular dependencies out of the box

Cons of TSyringe

  • Less flexible configuration options compared to TypeDI
  • Smaller community and ecosystem, with fewer third-party integrations
  • Limited documentation and examples compared to TypeDI

Code Comparison

TypeDI:

import { Container, Service, Inject } from 'typedi';

@Service()
class MyService {
  @Inject()
  private dependency: Dependency;
}

TSyringe:

import { injectable, inject, container } from "tsyringe";

@injectable()
class MyService {
  constructor(@inject("Dependency") private dependency: Dependency) {}
}

Both TypeDI and TSyringe are dependency injection containers for TypeScript. TypeDI offers more advanced features and configuration options, while TSyringe provides a simpler API backed by Microsoft. TypeDI has a larger community and more extensive documentation, but TSyringe handles circular dependencies better. The choice between the two depends on project requirements and personal preference.

16,828

AdonisJS is a TypeScript-first web framework for building web apps and API servers. It comes with support for testing, modern tooling, an ecosystem of official packages, and more.

Pros of AdonisJS

  • Full-featured web framework with built-in ORM, authentication, and more
  • Robust CLI for scaffolding and development tasks
  • Strong TypeScript support with decorators and IoC container

Cons of AdonisJS

  • Steeper learning curve due to its comprehensive nature
  • Potentially overkill for smaller projects or microservices
  • Less flexibility compared to lightweight DI solutions

Code Comparison

TypeDI:

import { Container, Service } from 'typedi';

@Service()
class UserService {
  // Service implementation
}

const userService = Container.get(UserService);

AdonisJS:

import { inject } from '@adonisjs/fold'

class UserController {
  @inject()
  public userService: UserService

  public async index() {
    // Controller logic using userService
  }
}

Summary

TypeDI is a lightweight dependency injection container for TypeScript, while AdonisJS is a full-featured web framework. TypeDI offers more flexibility and is easier to integrate into existing projects, whereas AdonisJS provides a complete ecosystem with built-in features like ORM, authentication, and routing. Choose TypeDI for simpler DI needs or when working with microservices, and AdonisJS for building robust, full-stack applications with a structured approach.

3,525

Extremely powerful Inversion of Control (IoC) container for Node.JS

Pros of Awilix

  • More flexible container API with support for various resolution strategies
  • Built-in support for auto-loading modules and creating containers from glob patterns
  • Lighter weight and faster performance in some scenarios

Cons of Awilix

  • Less TypeScript-focused, with weaker type inference in some cases
  • Steeper learning curve due to more configuration options and resolution strategies
  • Lacks some advanced features like circular dependency detection

Code Comparison

TypeDI:

@Service()
class UserService {
  constructor(private repository: UserRepository) {}
}

Container.get(UserService);

Awilix:

const container = awilix.createContainer();
container.register({
  userService: awilix.asClass(UserService),
  userRepository: awilix.asClass(UserRepository)
});

container.resolve('userService');

Both TypeDI and Awilix are popular dependency injection containers for JavaScript/TypeScript applications. TypeDI is more focused on TypeScript and decorator-based DI, while Awilix offers a more flexible API with various registration and resolution strategies. TypeDI provides stronger type inference out of the box, but Awilix offers more advanced features like auto-loading modules and creating containers from glob patterns. The choice between the two depends on specific project requirements, TypeScript usage, and desired level of configuration flexibility.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

TypeDI

Build Status codecov npm version Dependency Status

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:

  • property based injection
  • constructor based injection
  • singleton and transient services
  • support for multiple DI containers

Installation

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!

Basic Usage

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.
    public 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

Documentation

The detailed usage guide and API documentation for the project can be found:

Contributing

Please read our contributing guidelines to get started.

NPM DownloadsLast 30 Days