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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@woubuc/inject

v1.0.1

Published

Dead-simple dependency injection library

Downloads

3

Readme

Dependency Injection Container

A simple global dependency injection container

Basic usage

Simply annotate a service with @injectable() to register it.

Use the inject() function to get the singleton instance of the service. The DI container will automatically construct an instance of the injected class the first time it is injected anywhere.

import { injectable, inject } from '@woubuc/inject';

@injectable()
class MyService {
  doStuff() {}
}

class OtherService {
  private readonly service = inject(MyService);

  public doStuff() {
    this.service.doStuff();
  }
}

Custom tokens

You can use strings or symbols as injection tokens, instead of classes.

import { inject, injectable } from '@woubuc/inject';

const token = 'foo';

@injectable({ token })
class MyService {
  doStuff() {}
}

class OtherService {
  private readonly service = inject<MyService>(token);

  public doStuff() {
    this.service.doStuff();
  }
}

Note: always prefer class injection tokens as they are automatically strongly typed.

The DI Container

You can get a reference to the current container with Container.current(). This allows you to do more dynamic things with the container, besides simply injecting.

Get (inject)

The simple inject() function is actually shorthand for Container.current().get():

import { Container, injectable } from '@woubuc/inject';

@injectable()
class MyService {
  doStuff() {}
}

class OtherService {
  private readonly service = Container.current().get(MyService); // The long version

  public doStuff() {
    this.service.doStuff();
  }
}

Provide

Use provide() to provide custom data for a given injection token. Combined with string tokens, this can be used to provide e.g. configuration values.

import { Container, inject } from '@woubuc/inject';

const urlToken = Symbol('urlToken');

Container.current().provide(urlToken, 'http://example.com/');

class MyApiClientService {
  private readonly url = inject<string>(urlToken);

  public async load() {
    await fetch(this.url);
  }
}

Example: mocking injectables

You can use provide() to provide mock classes for tests.

// Main app
import { inject, injectable } from '@woubuc/inject';

@injectable()
class ApiService {
  public get() {
    return fetch('http://example.com');
  }
}

@injectable()
class TestableService {
  private api = inject(ApiService);

  public async load() {
    this.api.get(); // Does a fetch request
  }
}

//
// In your tests:
//
import { Container } from './lib.js';

test('my test', (t) => {
  class MockApiService {
    public get() {
      return {}; // Doesn't do a fetch request
    }
  }

  // Provide the mock implementation
  Container.current().provide(ApiService, new MockApiService());

  inject(TestableService).load(); // Doesn't do fetch request when calling api.get()
});

Scoped containers

Use scoped() to create a scoped child container and run (async) logic in it.

import { Container, inject } from '@woubuc/inject';

// Inject (and instantiate) an injectable in the global container
inject(MyService);

// Run some code in a local scoped container
await Container.current().scoped('temp-0', () => {
  // When we ask for the same class, the container will see that an instance
  // of it exists in the parent container (global) and return that instance.
  inject(MyService);

  // When we ask for a class that isn't instantiated yet, a new instance will
  // be created in the current container scope.
  inject(OtherService);
});

// Trying to inject the other service in the global container, even after
// injecting it successfully in the scoped container, will create a new instance
// because the global container has no idea what happened in the scoped container.
inject(OtherService);

Optional injectables

When using scoped() and/or provide(), sometimes you may have services that might or might not exist (yet). In that case you can use injectOptional() (or Container.current().tryGet()) to return undefined if no instance of the injectable exists yet - instead of constructing a new instance.

import { Container, injectOptional } from '@woubuc/inject';

const token = 'foo';

injectOptional(token); // undefined

Container.current().provide(token, 'hello world');

injectOptional(token); // 'hello world'

Destructors

If you need to run some cleanup logic when an instance is no longer needed (particularly useful when working with scoped containers), you can implement the OnDestroy interface.

import { Container, inject, injectable, type OnDestroy } from '@woubuc/inject';

@injectable()
class MyService implements OnDestroy {
  public constructor() {
    console.log('hello');
  }

  public onDestroy() {
    console.log('bye');
  }
}

await Container.current().scoped('test', () => {
  let service = inject(MyService); // "hello"

  // We're at the end of the scope so the container is deleted
  // and all local injectable instances are cleared.
  // "bye"
});