🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Book a DemoInstallSign in
Socket

singleton-injection

Package Overview
Dependencies
Maintainers
0
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

singleton-injection

A simple way to manage singletons in TypeScript projects

2.0.0
latest
Source
npm
Version published
Weekly downloads
4
33.33%
Maintainers
0
Weekly downloads
 
Created
Source

Singleton Injection

A simple way to manage singletons

This provides a way to create Singleton Container to store Singleton instances

Usage

// container.ts
import { SingletonContainer } from "singleton-injection";

// Define your singletons
const singletonMap = {
    shape: () => new Circle() as Shape,
    otherShape: () => new Square() as Shape
};

// Create Singleton container
export const container = new SingletonContainer(singletonMap);

// app.ts
// Get instance in your app with
import { container } from "./container";

// now you can get same instance of shape anywhere in your code
const shape = container.resolve("shape");
// you will get TS suggestions for parameter of `resolve`, so no need to worry about spelling mistakes

// Destroy container instances
container.destroy();
// after destroy, container.resolve will create and return new instances

Mocking in Tests

container.mock({
    shape: () => new MockedSquare() as Shape
});
// With above all `container.resolve("shape")` calls will return this mocked shape
// Note: mocked instances are not singletons, it will create instance everytime

// To restore mock, you can use same method with empty object, this will restore the original container
container.mock({});

Keywords

Singleton

FAQs

Package last updated on 03 Mar 2025

Did you know?

Socket

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.

Install

Related posts