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

ts-lazy-container

v1.0.0

Published

Tool for lazy dependency injection

Downloads

227

Readme

ts-lazy-container

This tool manages the creation and distribution of application-wide instances. These are created as singletons or unique variants as needed from provided instructions. In addition, scopes can be used to refine the distribution

npm version License: MIT npm downloads

Features

  • global dependency injection
  • lazy instance injection (create instances on demand)
  • class based provisioning/registration
  • injection key for type/interface based provisioning/registration
  • singleton or unique instance injection
  • refined distribution by isolated and inherited scopes (custom, flexible, fine-grained, encapsulated instance injection)
  • auto dependecy resolution (use provided/registered instructions to resolve object based class contructor parameters)

Installation

npm i ts-lazy-container

Usage

LazyContainer is lazy by design (as the name suggests). Instances will be created on demand during injection. For this to work, types, interfaces or classes must be registered to the container via creation instructions.

Injection Modes

  • singleton: created instance will be cached and reused on further injections. Dependencies (e.g. constructor parameters) are resolved in 'singleton' mode, too
  • unique: creates a unique instance on each injection. Dependencies (e.g. constructor parameters) are resolved in 'singleton' mode and are therefore NOT unique
  • deep-unique: creates a unique instance on each injection. Dependencies (e.g. constructor parameters) are resolved in 'deep-unique' mode and are therefore also unique

Register creation instructions

Identifier = Class or InjectionKey

Use provide() and/or provideClass() to register creation instructions.

  • With provide it is possible to register any Type, Interface or Class by using an InjectionKey as identifier. You can also register Classes without an InjectionKey, just use the Class itself as identifier. You must specify an additional callback function that creates an instance (must match the identifier type).
  • provideClass is specialized on class based registrations, it determines required constructor parameters that must be provided as well. Object-based constructor parameters do not require concrete instances but must be configured via identifiers. The container automatically resolves these identifiers when inject() is used to gain an instance (lazy), so they must also be registered in the container via provide or provideClass.

Identifiers can only be registered once. Duplicate registration will result in an error. If multiple instances of a type are needed, different InjectionKeys of the same type must be created.

Scoping

Scopes allow you to create tree structures within containers. This makes it possible to inject unique instances for specific use cases. These scopes can be created isolated or inherited. A scope is also just a container, so a scope can be created within a scope (and so on...).

  • inherited: An inherited scope can resolve instances from its parent. So when the scope tries to inject/resolve an instance (and its dependencies), it first looks for a provided instrution in the scope itself. If none is found, it tries to load it from the parent.
  • isolated: An isolated scope cannot access its parent. Therefore, it cannot access its registed instruction and all required instructions must be provided in the scope itself

Application Examples

Types and classes for all example variants

type TypedA = {
  text: string;
  flag: boolean;
  callback: () => void;
};

class A implements TypedA {
  constructor(
    public text: string,
    public flag: boolean,
    public callback: () => void
  ) {}
}

class DependsOnA {
  constructor(public a: TypedA, public list: number[]) {}
}

Variant 1

Register a class that depends on another (using provideClass)

import { LazyContainer } from 'ts-lazy-container';

const container = LazyContainer.Create();
container.provideClass(A, 'hello world', true, () => {});
container.provideClass(DependsOnA, A, [1, 2, 3, 42]);

// ...

const a = container.inject(A);
// => { text: 'hello world'; flag: true; callback: () => {} }
const doa = container.inject(DependsOnA);
// => { a: { text: 'hello world'; flag: true; callback: () => {} }; list: [1, 2, 3, 42] }

Variant 2

Mixed usage of provide and provideClass for class registration

import { LazyContainer } from 'ts-lazy-container';
const container = LazyContainer.Create();
container.provide(A, () => new A('hello world', true, () => {}));
container.provideClass(DependsOnA, A, [1, 2, 3, 42]);

// ...

const a = container.inject(A);
// => { text: 'hello world'; flag: true; callback: () => {} }
const doa = container.inject(DependsOnA);
// => { a: { text: 'hello world'; flag: true; callback: () => {} }; list: [1, 2, 3, 42] }

Variant 3

Use InjectionKeys to register/inject types or interfaces

import { injectionKey, LazyContainer } from 'ts-lazy-container';

const aInjectionKey = injectionKey<TypedA>();

const container = LazyContainer.Create();
container.provide(
  aInjectionKey,
  () => new A('hello world', true, () => {})
);
container.provideClass(DependsOnA, aInjectionKey, [1, 2, 3, 42]);

// ...

const a = container.inject(aInjectionKey); // a: TypedA
// => { text: 'hello world'; flag: true; callback: () => {} }
const doa = container.inject(DependsOnA);
// => { a: { text: 'hello world'; flag: true; callback: () => {} }; list: [1, 2, 3, 42] }

Variant 4

Use InjectionKeys to register/inject types or interfaces using anonymous objects

import { injectionKey, LazyContainer } from 'ts-lazy-container';

const aInjectionKey = injectionKey<TypedA>();

const container = LazyContainer.Create();
container.provide(aInjectionKey, () => ({
  text: 'hello world',
  flag: true,
  callback: () => {}
}));
container.provideClass(DependsOnA, aInjectionKey, [1, 2, 3, 42]);

// ...

const a = container.inject(aInjectionKey); // a: TypedA
// => { text: 'hello world'; flag: true; callback: () => {} }
const doa = container.inject(DependsOnA);
// => { a: { text: 'hello world'; flag: true; callback: () => {} }; list: [1, 2, 3, 42] }

Variant 5

Mix it all up!

  • use a class as creation instruction for an InjectionsKey
  • use different InjectionKeys to register multiple creation instructions of the same type/interface/class
import { injectionKey, LazyContainer } from 'ts-lazy-container';

const doa1InjectionKey = injectionKey<DependsOnA>();
const doa2InjectionKey = injectionKey<DependsOnA>();

const container = LazyContainer.Create();
container.provideClass(A, 'hello world', true, () => {});
container.provideClass(DependsOnA, A, [1, 2, 3, 42]);
container.provide(doa1InjectionKey, DependsOnA);
container.provide(
  doa2InjectionKey,
  () => new DependsOnA(container.inject(A), [5, 6, 7])
);

// ...

const doa1 = container.inject(doa1InjectionKey);
// doa1.list => [1, 2, 3, 42]
const doa2 = container.inject(doa2InjectionKey);
// doa2.list => [5, 6, 7]

Variant 6

Inject unique instances - use the correct mode

import { LazyContainer } from 'ts-lazy-container';

const container = LazyContainer.Create();
container.provideClass(A, 'hello world', true, () => {});
container.provideClass(DependsOnA, A, [1, 2, 3, 42]);

// ...

const doa1 = container.inject(DependsOnA); // defaults to 'singleton'
const doa2 = container.inject(DependsOnA, 'singleton');
const doa3 = container.inject(DependsOnA, 'unique');
const doa4 = container.inject(DependsOnA, 'deep-unique');

// doa1 === doa2      => true
// doa1 === doa3      => false
// doa1 === doa4      => false
// doa1.a === doa2.a  => true
// doa1.a === doa3.a  => true
// doa1.a === doa4.a  => false

Variant 7

Using scopes for unique or use case related instances.

import { LazyContainer } from 'ts-lazy-container';

class User {
  constructor(public name: string, public doa: DependsOnA) {}
}

const container = LazyContainer.Create();

container.provideClass(A, 'hello world', true, () => {});
container.provideClass(DependsOnA, A, [1, 2, 3, 42]);
container.provideClass(User, 'Jack', DependsOnA);

const scientistScope = container.scope('scientist').inherited; // can resolve any instance from parent scope
scientistScope.provideClass(User, 'Daniel', DependsOnA);

const alienScope = container.scope('alien').isolated; // NO access to parent; need to register dependencies again
alienScope.provideClass(A, 'hello Chulak', false, () => {});
alienScope.provideClass(DependsOnA, A, []);
alienScope.provideClass(User, "Teal'c", DependsOnA);

// ...

const jack = container.inject(User);
const daniel = scientistScope.inject(User);
const tealc = alienScope.inject(User);

// jack === daniel              => false
// jack === tealc               => false
// jack.name                    => Jack
// daniel.name                  => Daniel
// tealc.name                   => Teal'c
// jack.doa === daniel.doa      => true
// jack.doa === tealc.doa       => false
// jack.doa.a.text              => hello world
// daniel.doa.a.text            => hello world
// tealc.doa.a.text             => hello Chulak

...