dependency injection demo

by Richard Hunter

HTML

<script src="https://unpkg.com/[email protected]/lib/injector.js"></script>
<h1>Simple example using Dependency Injection with Diogenes library from CDN</h1>

JavaScript

let injector = new Diogenes();

/*
	Declare a constructor function as normal. Dependencies will be passed in in the options object.
*/

class Foo {
  constructor(options) {
    this.bar = options.bar;
  }
  
  getBar() {
    console.log(this.bar.name);
  }
}

/*
Declare the dependencies that will be passed to the constructor function using service provider keys
*/

Foo.inject = ['bar'];

/* Create the dependent types, again, as normal constructors */

class Bar {
	constructor() {
  	this.name = 'I am Bar';
  }
}

/*  register all the service providers with the injector 
The first argument is the service provider key
The second argument is the service provider, here the constructor function,
The third argument is a constant that defines what kind of object we want
the injector to create. Here we tell the injector to treat the service provider as a constructor function.
*/
injector.register('foo', Foo, Diogenes.INSTANCE);
injector.register('bar', Bar, Diogenes.INSTANCE);

/*
Get an instance of foo from the injector
*/

let foo = injector.get('foo');

// now use it
foo.getBar(); // logs 'I am Bar' to console