npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

di-typescript-container

v1.0.1

Published

A powerful and flexible TypeScript dependency injection container

Readme

TypeScript Dependency Injection (DI) Container

A powerful and flexible TypeScript dependency injection container with support for:

  • Class, value, and factory bindings
  • Constructor, method, and property injection
  • Singleton, transient, and request-scoped lifetimes
  • Container hierarchy and child containers
  • Module system for organizing bindings
  • Conditional and asynchronous module loading
  • Middleware and AOP-style interceptors
  • Auto-injection of services without explicit binding
  • Token-based auto-injection for interface/implementation patterns
  • Lazy resolution and circular dependency handling

Installation

npm install di-typescript-container

Basic Usage

import "reflect-metadata";
import {
  container,
  Injectable,
  Inject,
  InjectionToken,
} from "di-typescript-container";

// Define a service
@Injectable()
class UserService {
  getUsers() {
    return ["Alice", "Bob", "Charlie"];
  }
}

// Define another service that depends on UserService
@Injectable()
class AppService {
  constructor(private userService: UserService) {}

  getGreeting() {
    const users = this.userService.getUsers();
    return `Hello ${users.join(", ")}!`;
  }
}

// Resolve the service from the container
const app = container.resolve(AppService);
console.log(app.getGreeting()); // "Hello Alice, Bob, Charlie!"

Core Features

Auto-Injection

Automatically register classes with the @Injectable() decorator:

// No explicit bindings needed!
@Injectable()
class UserService {
  getUsers() {
    return ["Alice", "Bob", "Charlie"];
  }
}

@Injectable()
class AppService {
  constructor(private userService: UserService) {}

  getGreeting() {
    return `Hello ${this.userService.getUsers().join(", ")}!`;
  }
}

// Create a container with auto-registration enabled (default)
const container = new DIContainer();

// Resolve without explicit binding registration
const app = container.resolve(AppService);
console.log(app.getGreeting()); // "Hello Alice, Bob, Charlie!"

Token-Based Auto-Injection

Register implementations for interfaces using tokens:

// Define an interface token
const USER_SERVICE = new InjectionToken<UserService>("UserService");

// Register implementation with token
@Injectable(USER_SERVICE)
class UserServiceImpl implements UserService {
  getUsers() {
    return ["Alice", "Bob", "Charlie"];
  }
}

@Injectable()
class AppService {
  constructor(@Inject(USER_SERVICE) private userService: UserService) {}

  getGreeting() {
    return `Hello ${this.userService.getUsers().join(", ")}!`;
  }
}

// No explicit binding needed - resolve by token
const app = container.resolve(AppService);

Binding Types

// Class binding
container
  .bind<UserService>(UserService)
  .toClass(UserService)
  .inSingletonScope();

// Value binding
const CONFIG_TOKEN = new InjectionToken<Config>("Config");
container.bind(CONFIG_TOKEN).toValue({ apiUrl: "https://api.example.com" });

// Factory binding
container
  .bind<Database>(Database)
  .toFactory((ctx) => {
    const config = ctx.resolve(CONFIG_TOKEN);
    return new Database(config.dbConnectionString);
  })
  .inSingletonScope();

Injection Decorators

@Injectable()
class EmailService {
  constructor(
    // Standard injection based on type
    private userService: UserService,

    // Token-based injection
    @Inject(CONFIG_TOKEN) private config: Config,

    // Optional dependency
    @Optional() private logger?: Logger,

    // Named dependency
    @Named("admin") private adminUserService?: UserService
  ) {}
}

Scope Management

// Singleton - shared instance for all consumers
container
  .bind<UserService>(UserService)
  .toClass(UserService)
  .inSingletonScope();

// Transient - new instance each time it's resolved
container
  .bind<RequestHandler>(RequestHandler)
  .toClass(RequestHandler)
  .inTransientScope();

// Request scope - same instance within a request context
container.bind<Session>(Session).toClass(Session).inRequestScope();

Child Containers

// Create a child container that inherits parent bindings
const childContainer = container.createChildContainer();

// Override a binding in the child container
childContainer.rebind<Logger>(Logger).toClass(CustomLogger);

Module System

import {
  ContainerModule,
  ConditionalModule,
  AsyncContainerModule,
} from "di-typescript-container";

// Create a module with related bindings
const userModule = new ContainerModule((container) => {
  container
    .bind<UserService>(UserService)
    .toClass(UserService)
    .inSingletonScope();
  container
    .bind<UserRepository>(UserRepository)
    .toClass(UserRepository)
    .inSingletonScope();
});

// Create a conditional module for environment-specific bindings
const devModule = new ConditionalModule(
  () => process.env.NODE_ENV === "development",
  (container) => {
    container.bind<Logger>(Logger).toClass(DevLogger).inSingletonScope();
  }
);

// Create an async module (e.g., for loading config)
const configModule = new AsyncContainerModule(async (container) => {
  const config = await loadConfigAsync();
  container.bind(CONFIG_TOKEN).toValue(config);
});

// Load modules
container.loadModules([userModule, devModule]);
await container.loadAsyncModule(configModule);

Advanced Features

Hierarchical Resolution

The container can resolve dependencies from its parent container if they're not found in the current container.

Circular Dependencies

The container handles circular dependencies using lazy loading:

// Define tokens for our interfaces
const SERVICE_A = new InjectionToken<ServiceA>("ServiceA");
const SERVICE_B = new InjectionToken<ServiceB>("ServiceB");

@Injectable(SERVICE_A)
class ServiceAImpl implements ServiceA {
  constructor(@Lazy(SERVICE_B) @Inject(SERVICE_B) private serviceB: ServiceB) {}

  // Implementation...
}

@Injectable(SERVICE_B)
class ServiceBImpl implements ServiceB {
  constructor(@Lazy(SERVICE_A) @Inject(SERVICE_A) private serviceA: ServiceA) {}

  // Implementation...
}

// Auto-injection handles the circular dependency
const serviceA = container.resolve(SERVICE_A);

Contextual Binding with Named Injections

container
  .bind<UserService>(UserService)
  .toClass(UserService)
  .inSingletonScope();
container
  .bind<UserService>("UserService:admin")
  .toClass(AdminUserService)
  .inSingletonScope();

@Injectable()
class UserController {
  constructor(
    private regularUserService: UserService,
    @Named("admin") private adminUserService: UserService
  ) {}
}

License

MIT