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

boxed-injector

v2.0.0

Published

Dependency Injection Tools

Downloads

354

Readme

NPM version Build Status Coverage Status

boxed-injector

Dependency Injection Tools

Installation

$ npm install --save boxed-injector

Overview

This is a set of lightweight Dependency Injection components that can be used in both client and server javascript code.

There are 2 components.

  1. Injector (Dependency Injection Container)
  2. Locator (Service Locator, which exposes the DI Container)

For client side development with React, there are additional helper utilities in boxed-injector-react

Installation

$ npm install --save boxed-injector

Usage


'use strict';

const parts = [];

class EngineFactory {
  static get inject() {
    return [
      'Parts'
    ];
  }
  constructor(parts) {
    this.parts = parts;
  }
}

class CarFactory {
  static get inject() {
    return [
      'EngineFactory'
    ];
  }
  constructor(engineFactory) {
    this.engineFactory = engineFactory;
  }
}

// Dependency Injection Container
const Injector = require('boxed-injector').Injector;
let injector = new Injector();

// Register instances
injector.register('Parts', parts);

// Register Factories
injector
  .factory('EngineFactory', EngineFactory)
  .factory('CarFactory', CarFactory);

const carFactory = injector.get('CarFactory');

console.log(carFactory);

// Service Locator - warning - this is a singleton!
const Locator = require('boxed-injector').Locator;
Locator.set(injector);
injector = Locator.get();

const sameCarFactory = injector.get('CarFactory');

console.log(sameCarFactory);
console.log(carFactory === sameCarFactory);

// injector.get('whatever');

Create

Resolves a factory's dependencies and then instantiates an instance with the given args. Will call the constructor (new) on a registered instance that is a function.

function Engine() {}
function Car(engine, color) { this.engine = engine; this.color = color; }
Car.inject = ['Engine'];
injector.factory('Engine', Engine);
injector.factory('Car', Car);
const car = injector.create('Car', ['blue']);
// { engine, engine, color: 'blue' }

Middleware

Middleware functions are executed every time a service is accessed from the container (or on a factory, the first time it's accessed). Global middlewares as well as service / factory specific middlewares are supported and are executed in the order of registry (FIFO). Note that registered instances are singletons and mutations will affect all consumers.

Middlewares are synchronous, and is passed an object as follows:

{
  name: 'ExampleService',
  depends: ['ThingItsDependentOn', 'OtherThing'],
  instance: { thing: {}, other: {} }, // fully instantiated instance,
  factory: ExampleService // factory
}

Usage:


const Injector = require('boxed-injector');
const injector = new Injector();

// will console log before getting any instance from the container
injector.middleware(entity => console.log('before global'));
// will console log 'baz' before getting baz from the container - will always run after global above
injector.middleware('baz', entity => console.log(entity.name));
// will console log for any instance, but will run after baz and above global is logged 
injector.middleware(entity => console.log(`before global again - resolving ${entity.name}`));

injector.register('baz', 'result');

// will console log AFTER getting any instance from the container
injector.middleware(() => console.log('after global'));
// will console log 'baz' AFTER getting baz from the container - will always run after global above
injector.middleware('baz', entity => console.log(entity.name));

injector.get('baz');

// -> before global
// -> baz
// -> before global again
// instance returned
// -> baz
// -> after global  

Advanced Usage


// call the function directly instead of calling new on it.
injector.factory('baz', () => {}, { function: true });

// declare dependencies during registration rather than on the function.
injector.factory('baz', () => {}, { depends: ['foo'] });

// dependency could be singular.
injector.factory('baz', () => {}, { depends: 'foo' });

// dependency could be singular.
injector.factory('baz', () => {}, { depends: 'foo' });

injector.factory('d', x => x, {depends: 'c', function: true});
// etc...

// graph returns a 
injector.graph('d');
// ['d', 'c', 'b', 'a']

// true or false if the injector has a service/factory registered.
injector.has('foo');

// like injector.register, but actually replaces the instance (no guard)
injector.set('foo', 'bar');

Contributing

We look forward to seeing your contributions!

License

MIT © Ben Lugavere