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

inversify-typesafe-spring-like

v0.5.9

Published

Add-On Library for inversify-typesafe to make it more like Spring.

Readme

import { ApplicationContext, BeanConfig, returnAutowired } from "inversify-typesafe-spring-like";

interface Article {
  id: number;
  title: string;
  content: string;
}

interface ArticleOutgoingPort {
  getById(id: number): Promise<Article>
}

class ArticleRepository implements ArticleOutgoingPort {
  getById(id: number): Promise<Article> {
    return Promise.resolve({
      id: id,
      title: `title #${id}`,
      content: `content #${id}`,
    })
  }
}

interface GetArticleUseCase {
  execute(id: number): Promise<Article>
}

const { Autowired } = returnAutowired<Beans>();

class ArticleQueryService implements GetArticleUseCase {
  constructor(
    @Autowired("ArticleOutgoingPort") // compile error if a parameter of @Autowired is not a key of Beans.
    private readonly articleOutgoingPort: ArticleOutgoingPort,
  ) { }
  execute(id: number): Promise<Article> {
    return this.articleOutgoingPort.getById(id);
  }
}

type Beans = {
  GetArticleUseCase: GetArticleUseCase; // interface (class is also possible)
  ArticleOutgoingPort: ArticleOutgoingPort; // interface (class is also possible)
}

const beanConfig: BeanConfig<Beans> = {
  // compile error if ArticleQueryService is not compatible with GetArticleUseCase.
  GetArticleUseCase: (bind) => bind().to(ArticleQueryService),
  // compile error if ArticleRepository is not compatible with ArticleOutgoingPort.
  ArticleOutgoingPort: (bind) => bind().to(ArticleRepository), 
}

const applicationContext = ApplicationContext(beanConfig);

const getArticleUseCase = applicationContext.get("GetArticleUseCase")

getArticleUseCase.execute(1).then(console.log)

TL;DR

inversify-typesafe-spring-like is a Spring-flavored add-on for inversify-typesafe. Define a Beans map, register every bean with BeanConfig, create an Autowired decorator with returnAutowired, and initialize the container with ApplicationContext. Bean names are checked and return types are inferred at compile time, while beans use singleton scope by default.

  • Define one Beans map whose string keys are bean names and whose values are the types returned for those names.
  • Declare a BeanConfig<Beans> containing every key in Beans, and bind each key to a compatible implementation with the provided bind() function.
  • Create a project-local decorator by destructuring const { Autowired } = returnAutowired<Beans>(), then use @Autowired("BeanName") for constructor injection.
  • Pass the bean config to ApplicationContext; let TypeScript infer the context type instead of adding a generic argument manually.
  • Resolve beans with applicationContext.get("BeanName"). Do not cast bean names or result types, because doing so bypasses compile-time checks.
  • Assume singleton scope unless an explicit ContainerOptions argument passed to ApplicationContext overrides defaultScope.
  • Use the underlying inversify-typesafe capabilities for advanced bindings and the original InversifyJS API. BeanConfig, ApplicationContext, and returnAutowired correspond to TypesafeServiceConfig, createTypesafeContainer, and returnTypesafeInject respectively.
  • Keep the Beans map, bean config, get calls, and Autowired decorators synchronized whenever a bean is added, removed, or renamed.

Introduction

This library extends inversify-typesafe to provide a development experience similar to Spring Framework.

It sets the default container scope to Singleton and exports standard inversify-typesafe utilities with Spring-like naming conventions, making it easier for developers familiar with Spring to adopt Inversify in TypeScript projects.

Installation

Via npm

npm install inversify-typesafe-spring-like

Via yarn

yarn add inversify-typesafe-spring-like

Via pnpm

pnpm add inversify-typesafe-spring-like

Demo

Try it out on StackBlitz.

Types

https://inversify-typesafe-spring-like.myeongjae.kim/modules.html

Usage

The API is designed to mirror Spring's terminology:

  1. createTypesafeContext() $\rightarrow$ ApplicationContext()
    • Note: defaultScope is set to Singleton by default.
  2. returnTypesafeInject() $\rightarrow$ returnAutowired()
  3. TypesafeServiceConfig<T> $\rightarrow$ BeanConfig<T>

For complete usage documentation and advanced features, please refer to the inversify-typesafe documentation.

Advanced Patterns

Lazy ApplicationContext Initialization

In production applications, you may want to defer the initialization of the ApplicationContext until it's actually needed. This is especially useful in serverless environments or when you want to avoid initialization overhead during module loading.

The lazy utility function:

// core/common/util/lazy.ts
export const lazy = <T>(fn: () => T) => {
  let value: T | undefined;
  return () => value ?? (value = fn());
};

Usage with ApplicationContext:

// core/config/applicationContext.ts
import 'reflect-metadata';
import { ApplicationContext } from 'inversify-typesafe-spring-like';
import { beanConfig } from './beanConfig';
import { lazy } from '../common/util/lazy';

// Lazy initialization - ApplicationContext is created only when first accessed
export const applicationContext = lazy(() => ApplicationContext(beanConfig));

Using in controllers or services:

// app/api/articles/GetArticleController.ts
import { applicationContext } from '@/core/config/applicationContext';

export default async function handler(req: Request) {
  // ApplicationContext is initialized on first call, then reused
  const useCase = applicationContext().get("GetArticleUseCase");
  const article = await useCase.execute(req.params.id);
  return Response.json(article);
}

Why use lazy initialization?

| Benefit | Description | |---------|-------------| | Faster cold starts | Module loading doesn't trigger DI container initialization | | On-demand creation | Container is only created when actually needed | | Singleton guarantee | Multiple calls return the same instance | | Testability | Easy to mock or replace in tests |

Without lazy (eager initialization):

// ❌ Container is created immediately when module is imported
export const applicationContext = ApplicationContext(beanConfig);

// Every import of this module triggers initialization
import { applicationContext } from './applicationContext';

With lazy (deferred initialization):

// ✅ Container is created only when applicationContext() is called
export const applicationContext = lazy(() => ApplicationContext(beanConfig));

// Import doesn't trigger initialization
import { applicationContext } from './applicationContext';

// Initialization happens here, on first use
const useCase = applicationContext().get("GetArticleUseCase");

Note: The lazy function ensures the initialization function is called exactly once, and subsequent calls return the cached value.

Domain-Specific BeanConfig

As your application grows, you may want to organize beans by domain. This pattern allows each domain module to define its own beans while extending a common configuration.

// core/config/CommonBeanConfig.ts
import { BeanConfig } from "inversify-typesafe-spring-like";

interface LoggingPort {
  log(message: string): void;
}

class ConsoleLogger implements LoggingPort {
  log(message: string): void {
    console.log(`[LOG] ${message}`);
  }
}

export type CommonBeans = {
  LoggingPort: LoggingPort;
};

export const commonBeanConfig: BeanConfig<CommonBeans> = {
  LoggingPort: (bind) => bind().to(ConsoleLogger),
};
// core/article/config/ArticleBeanConfig.ts
import { BeanConfig, returnAutowired } from "inversify-typesafe-spring-like";
import { CommonBeans, commonBeanConfig } from "../config/CommonBeanConfig";

interface ArticleQueryPort { /* ... */ }
interface ArticleCommandPort { /* ... */ }
interface GetArticleUseCase { /* ... */ }

// Extend CommonBeans with domain-specific beans
export type ArticleBeans = CommonBeans & {
  ArticleQueryPort: ArticleQueryPort;
  ArticleCommandPort: ArticleCommandPort;
  GetArticleUseCase: GetArticleUseCase;
};

// Domain-specific Autowired decorator
export const { Autowired: ArticleAutowired } = returnAutowired<ArticleBeans>();

export const articleBeanConfig: BeanConfig<ArticleBeans> = {
  ...commonBeanConfig,  // Include common beans
  ArticleQueryPort: (bind) => bind().to(ArticlePersistenceAdapter),
  ArticleCommandPort: (bind) => bind().to(ArticlePersistenceAdapter),
  GetArticleUseCase: (bind) => bind().to(ArticleQueryService),
};
// Usage in domain service
class ArticleQueryService implements GetArticleUseCase {
  constructor(
    @ArticleAutowired("ArticleQueryPort")  // Type-safe within ArticleBeans
    private readonly articleQueryPort: ArticleQueryPort,
    @ArticleAutowired("LoggingPort")  // Common beans are also available
    private readonly loggingPort: LoggingPort,
  ) { }
}

Benefits:

  • Each domain owns its bean configuration
  • Common beans (logging, transactions, etc.) are shared across domains
  • Type safety is maintained within each domain's scope
  • Easy to identify which beans belong to which domain

Reusing a Single Class for Multiple Interfaces with toResolvedValue

When a single class implements multiple interfaces (e.g., both QueryPort and CommandPort), you can use toResolvedValue to register the same instance under different bean names. This avoids creating separate instances and ensures consistency.

import { ApplicationContext, BeanConfig, returnAutowired } from "inversify-typesafe-spring-like";

// Interfaces
interface StayQueryPort {
  findById(id: number): Promise<Stay | null>;
  findAll(): Promise<Stay[]>;
}

interface StayCommandPort {
  save(stay: Stay): Promise<Stay>;
  delete(id: number): Promise<void>;
}

// Single class implementing both interfaces
class StayPersistenceAdapter implements StayQueryPort, StayCommandPort {
  async findById(id: number): Promise<Stay | null> { /* ... */ }
  async findAll(): Promise<Stay[]> { /* ... */ }
  async save(stay: Stay): Promise<Stay> { /* ... */ }
  async delete(id: number): Promise<void> { /* ... */ }
}

type Beans = {
  StayQueryPort: StayQueryPort;
  StayCommandPort: StayCommandPort;
};

const { Autowired } = returnAutowired<Beans>();

const beanConfig: BeanConfig<Beans> = {
  // Register the class for the first interface
  StayQueryPort: (bind) => bind().to(StayPersistenceAdapter),

  // Reuse the same instance for the second interface
  StayCommandPort: (bind) =>
    bind().toResolvedValue(
      (queryPort) => queryPort as StayCommandPort,  // Transform function
      ['StayQueryPort']  // Dependencies to resolve first
    ),
};

const applicationContext = ApplicationContext(beanConfig);

// Both return the same instance
const queryPort = applicationContext.get("StayQueryPort");
const commandPort = applicationContext.get("StayCommandPort");

console.log(queryPort === commandPort);  // true (same instance)

How toResolvedValue works:

bind().toResolvedValue(transformFn, dependencies)
  • transformFn: A function that receives the resolved dependencies and returns the value to bind
  • dependencies: An array of bean names to resolve before calling the transform function

Use cases:

  • Single class implementing multiple interfaces (CQRS pattern)
  • Creating derived beans from existing beans
  • Aliasing beans under different names
  • Lazy transformation of resolved dependencies

Benefits:

  • Avoids duplicate instances when the same class serves multiple roles
  • Maintains singleton behavior across interface boundaries
  • Clear dependency declaration for complex wiring scenarios

License

MIT © Myeongjae Kim