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

a-di

v1.0.25

Published

Dependency injection library for Javascript/Typescript

Downloads

118

Readme

Yet another Dependency Injection Library for JavaScript

Highly inspired by Autofac.NET

We have tried to accommodate all the best DI and IoC practices for JavaScript

const di = new Di;

1 Registration

The greatest challenge for DI frameworks in JavaScript is to get the list of dependencies for a constructor, method, etc. JavaScript is not statically typed, so here other ways should be found to declare the dependencies. And we also try to follow the 1st rule of any di framework - "Your classes should not be dependent on the DI itself".

Though you can use it as a Service Locator

When registering the component, you specify identifiers, by which the dependency is resolved. It can be some another Type, string identifier. But we do not encourage you to use string identifiers.

It is also possible to get the instance without having previously to register the Type

const foo = di.resolve(Foo);

Later you can register another Type for this one.

1.1 Type

Class constructor;

class Foo {
    constructor (bar, qux) {}
}

1.2 Instance

Pass already instantiated class to the container, and it will be used by all dependents

di.registerInstance(new Foo(di.resolve(IBar), di.resolve(IQux))).as(IFoo);

// or use Initializer wich will be called on first `IFoo` require.
di.registerInstance(IBar, IFoo, (bar, foo) => new Foo(bar, foo)).as(IFoo);

// you can even suppress the lamda here
di.registerInstance(IBar, IFoo, Foo).as(IFoo);

1.3 Factory

Register a function which will create the instance on demand. Is similar to instance initializer, but the factory is called every time the dependency is required.

di.registerFactory(IBar, (bar) => {}).as(IFoo);

// No arguments are defined - we pass the di itself, for the case your factory method is out of the current di scope.
di.registerFactory(di => {}).as(IFoo);

2 Dependency definitions

2.1 Constructor

2.1.1 External definitions

From the previous paragraph you have already seen using method, when registering the Type. Here we define what identifiers should be used to instantiate the instance.

Pros: Your implementation is fully decoupled from the DI and the registration itself.

class Foo {
    constructor (logger) { logger.log() }
}
// ----
class Bar {
    log (...args) { console.log(...args) }
}
// ---
class ILog { log () {} }
// ---
di
    .registerType(Bar)
    .as(ILog);
di
    .registerType(Foo)
    .using(ILog)
    .asSelf()
    .onActivated(foo => console.log(foo));

2.1.2 Decorators

Pros: In-place configuration, but has reference to the di instance

class Foo {
    constructor (@di.inject(ILog) logger) {
        logger.log()
    }
}

2.1.3 Default parameters

Pros: new Foo() also works

class Foo {
    constructor (logger = di.resolve(ILog)) {
        logger.log()
    }
}

2.1.4 In-place meta information

Maybe most irrelevant feature, but anyway

Pros: Your implementation is decoupled from the DI, but holds meta information for the DI library.

Per default we read the static $inject property on the Type

class Foo {
    static $constructor = [ ILog ]

    constructor (logger) { logger.log() }
}

You can override the reader and provide us with the Identifiers for injection.

const CustomMetaReader = {
    getConstructor (Type) {
        return Type.$inject;
    }
};
di.defineMetaReader(CustomMetaReader);
// ----
class Foo {
    static $inject = [ILog]
    constructor (logger) { logger.log() }

}

2.1.5 Other ways

💬 Do you have any ideas? Please share them via issues.

TypeScript: initially, this project targets plain JavaScript, but TypeScript is preferred.

2.2 Properties

Property injections are supported by Types components.

2.2.1 External definitions

class Foo {
    constructor () {
        this.logger = new DummyLogger();
    }
    doSmth () {
        this.logger.log();
    }
}
// ---
di
    .registerType(Foo)
    .properties({
        // DummyLogger will be replaced with the registration for ILog
        logger: ILog
    })
    .asSelf();

2.2.2 In-place meta information

Per default we read the static $properties to get the key: Identifier information.

class Foo {
    constructor () { }
}
Foo.$properties = {
    logger: ILog
};
// ----
di
    .registerType(Foo)
    .asSelf();

You can override the reader and provide us with the Identifiers for injection.

let CustomMetaReader = {
    getProperties (Type) {
        // return hash with {key: Identifier}
    }
};
di.defineMetaReader(CustomMetaReader);

2.2.3 Other ways

💬 Ideas about better API - please share!


2.3 Methods

Injections into Type_s_functions.

2.3.1 External definitions

class Foo {
    doSmth (logger) {
        logger.log();
    }
}
// ---
di
    .registerType(Foo)
    .methods({
        // The method on an instance can be the called without any arguments
        // Di will provide required dependencies to the inner function
        doSmth: [ILog]
    })
    .asSelf();

2.3.2 In-place meta information

Per default we read the static $methods with key:[Identifier, ...] information.

class Foo {
    doSmth (logger) { logger.log() }

    static $methods = {
        doSmth: [ ILog ]
    };
}
// ----
di
    .registerType(Foo)
    .asSelf();

You can override the reader and provide us with the Identifiers for injection.

const CustomMetaReader = {
    getMethods (Type) {
        // return hash with {key: [Identifier, ...]}
    }
};
di.defineMetaReader(CustomMetaReader);

2.3.3 Other ways

💬 Ideas about better API - please share!


3 Consume

3.1 Initialize registered components

We inject all dependencies and return ready to use component.

let x = di.resolve(IFoo);

3.2 Create inherited classes

The inherited class accepts empty constructor, in this case we will pass the resolved components to the base class.

let FooWrapper = di.wrapType(IFoo);
let foo = new FooWrapper();

3.3 Create function delegates

Define function argument identifiers, and you can call the function without arguments.

let myFunction = di.wrapFunction(IFoo, IBar, (foo, bar) => {});
myFunction();

4 Additional configuration

4.1 Predefine parameter values

Sometimes it is needed to set values for parameters, which will be directly passed inside the function.

class Foo {
    constructor (bar, shouldDoSmth)
}
di
    .registerType(Foo)
    .using(Bar)
    .withParams(null, true)

1️⃣ Passing null values says the di library to resolve values from container by declared Type

2️⃣ Boolean true from sample just shows the idea of passing values. You may want to get the value from app configuration or some other source.

4.2 Configurate arguments

Arguments or values for a constructor/function are resolved from 3 sources:

  • Declared parameter values
  • Type definitions
  • Direct values from the current function call.

With options "ignore" "extend" "override" you can control how we handle the third source. Default is "override"

5 How do we use the library?

We rarely use all of those registration and configuration features.

  1. All the Services, Workers, Handlers, Factories - actually everything except Data Models - we use mostly as singletons. Means any initialization of an Instance we do via di.resolve. Note, that no configuration or registration is required - when nothing specified di initializes the class as-is.

We do this, while a class can memoize initialization, data, configuration, or method calls.

import { UserService } from './UserService'
// ....
let service = di.resolve(UserService);
  1. To have more clear dependency tree structure, we define some dependencies via constructor as default parameters:
import { UserService } from './UserService'
// ....
class Foo {
    constructor (
        private service = di.resolve(UserService)
    )
}
  1. For multiple implementations we use abstract classes.
abstract class AFoo {
    abstract log ()
    // ... some common logic
}

// Option 1. Register the implementation as a default for the base (AFoo)
@di.for(AFoo)
class SomeFoo extends AFoo () {}

// Option 2. Without the decorator, the type could be registered later somewhere in code:
di.registerType(AFoo).for(AFoo)


//# Usage 1
class UserService {
    constructor (
        foo = di.resolve(AFoo)
    ) {}
}

//# Usage 2
class UserService {
    constructor (
        @di.inject(AFoo) foo: AFoo
    ){}
}

🏁


©️ MIT — 2021 Atma.js Project