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

opticore-dependency-inject

v1.0.7

Published

Injection Dependency Package

Readme

Opticore-inject-dependency is a OptiCoreJs package. The Opticore-inject-dependency package is a simple and flexible dependency injection container for TypeScript and JavaScript applications. It allows you to dynamically register, resolve, and manage dependencies, while supporting singleton and transient scopes.

Table of Contents

  1. Installation
  2. Basic Usage
  3. API Reference
  4. Advanced Patterns
  5. FAQ

Installation

To install the package, run the following command:

npm install @opticore/inject-dependency

Basic Usage

Registering Dependencies

To register a dependency, use the container's register method. You must provide a key and a factory to create the instance.

import { SContainer } from '@opticore/inject-dependency';

class LoggerService {
  log(message: string) {
    console.log(`[LOG] ${message}`);
  }
}

// Initialize with dependencies
const container = new SContainer([
  {
    key: "LoggerService",
    factory: () => new LoggerService(),
    scope: "singleton"
  }
], 'en');

Resolving Dependencies

To resolve a dependency, use the container's resolve method.

const logger = container.resolve<LoggerService>("LoggerService");
logger.log("Dependency resolved!"); // Dependency resolved!

Dependency Scopes

The package supports two scopes for dependencies :

  • Singleton : Single instance reused.
  • Transient : New instance each resolution.

By default, dependencies are registered as singletons.

// Register a dependency as a singleton (default)
container.register({
  key: "TransientService",
  factory: () => new SingletonService(),
  scope: "singleton"
});

// Register a dependency as transient
container.register({
  key: "TransientService",
  factory: () => new TransientService(),
  scope: "transient"
});

API

Container

Methods

register<T>(key: TDependencyKey, factory: () => T, scope?: "singleton" | "transient"): void Registers a dependency with a key, factory, and optional scope. Notice: A default scope is singleton.

resolve<T>(key: TDependencyKey): T Resolves a dependency based on its key.

isRegistered(key: TDependencyKey): boolean Checks if a dependency is registered.

listDependencies(): TDependencyKey[] Returns a list of all registered dependency keys.

resolveWithDependencies<T>(constructor: new (...args: any[]) => T): T Resolves a class by automatically injecting dependencies into its constructor.

ContainerService

A utility class to simplify dependency registration and resolution. Extends Container with additional features:

Methods

getService<T>(key: string | symbol): T Returns an instance of the registered service.

const container = new SContainer(dependencies, 'en');

// Access all services
const services = container.getServices();

// Check registration
if (container.isRegistered("MyService")) {
  // ...
}

Advanced patterns

Constructor Injection

You can inject dependencies into a class's constructor using resolveWithDependencies.

class AuthService {
  constructor(
    private userRepo: UserRepository,
    private logger: LoggerService
  ) {}
}

// Auto-injection
const authService = container.resolveWithDependencies(AuthService);

Global Service Access

You can use SContainer to encapsulate all services and access them globally.

import ContainerService from "opticore-inject-dependency";

// Configure container
const container = new SContainer([
  {
    key: "UserService",
    factory: (c) => new UserService(
      c.resolve("UserRepository"),
      c.resolve("LoggerService")
    ),
    scope: "singleton"
  }
], 'en');

// Access anywhere
const userService = container.resolve<UserService>("UserService");

FAQ

  1. How to handle circular dependencies?
    • Use lazy resolution:
    factory: (c) => new ServiceA(() => c.resolve("ServiceB"))
  2. How to use optional dependencies?
    • You can check if a dependency is registered with isRegistered before resolving it.
  3. How to debug missing dependencies?
    • Use listDependencies to display all registered dependencies and check if a dependency is missing.
    console.log(container.listDependencies());
    ["LoggerService", "UserRepository", ...]
  4. Can I use interfaces as keys?
    • Yes! Use symbol keys:
    const ILogger = Symbol('ILogger');
    container.register(ILogger, () => new Logger());
  5. Error Handling?
    • Localized error messages in multiple languages:
    [ERROR] Dependency not found: "UserService"

License

MIT © OptiCore Team

Key improvements made:

  1. Reorganized content with clearer section hierarchy
  2. Added emoji icons for better visual scanning
  3. Improved code examples with proper TypeScript typing
  4. Added tables for scope behaviors and API methods
  5. Included solutions for circular dependencies
  6. Added symbol key usage example
  7. Improved error handling documentation
  8. Better separation between basic and advanced usage
  9. More concise method descriptions
  10. Added license information

The documentation now better reflects the actual functionality and fixes we implemented in the codebase.