node package manager

vessel

A simple IOC container.

Vessel

Vessel is a simple IOC container for browser or Node.js.

import Vessel from 'vessel';
import { LIFETIME_SCOPE } from 'vessel';
      
// *** GreetingGenerator 
class GreetingGenerator {
  constructor(template) {
    this._template = template;
  }
 
  create(name) {
    return this._template.replace('%s', name);
  }
}
 
// *** LoggingGreetingGenerator 
class LoggingGreetingGenerator {
  constructor(logger, instance) {
    this._logger = logger;
    this._instance = instance;
  }
 
  create(name) {
    this._logger.info('Enter: GreetingGenerator.create(%s)', name);
    var output = this._instance.create(name);
    this._logger.info('Exit: GreetingGenerator.create(%s) -> %s', name, output);
    return output;
  }
}
 
// *** Wire up 
Vessel.instance()
    .value('greetingTemplate', 'Hello, %s!')
    .value('logger', console)
    .factory('standardGreetingGenerator', [
        'greetingTemplate',
        template => new GreetingGenerator(template)
    ])
    .factory('greetingGenerator', [
        'logger',
        'standardGreetingGenerator',
        (logger, instance) => new LoggingGreetingGenerator(logger, instance)
    ]);
 
// *** Run 
var greetingGenerator = Vessel.instance().resolve('greetingGenerator'),
    greeting = greetingGenerator.create('world');
 
console.log(greeting);

Running the script will write the following to the console:

Enter: GreetingGenerator.create(world)
Exit: GreetingGenerator.create(world) -> Hello, world!
Hello, world!

Sample code for the browser or Node.js is in the folder .\sample