Skip to content

Instantly share code, notes, and snippets.

@alejofernandez
Forked from jankuca/injector.js
Created June 2, 2013 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alejofernandez/5693758 to your computer and use it in GitHub Desktop.
Save alejofernandez/5693758 to your computer and use it in GitHub Desktop.
/**
* @constructor
*/
function Injector() {
/**
* @type {!Object.<string, function(Injector=): !Object>}
*/
this.factories = {};
/**
* @type {!Object.<string, !Object>}
*/
this.services = {
'$injector': this
};
}
/**
* Adds a service factory.
* @param {string} key A service key.
* @param {function(Injector=): !Object} factory A service factory.
*/
Injector.prototype.addService = function (key, factory) {
this.factories[key] = factory;
};
/**
* Returns a service by its key.
* @param {string} key The key of the service to get.
* @return {!Object} The service.
*/
Injector.prototype.getService = function (key) {
var service = this.services[key];
if (!service) {
var factory = this.factories[key];
if (!factory) {
return null;
}
service = factory();
this.services[key] = service;
}
return service;
};
/**
* Instantiates the given constructor providing it with its dependencies.
* @param {Function} Constructor The constructor function to use.
* @return {!Object} An instance of the constructor.
*/
Injector.prototype.create = function (Constructor) {
var Dependant = function () {};
Dependant.prototype = Contructor.prototype;
var instance = new Dependant();
this.inject(Constructor, instance);
return instance;
};
/**
* Injects dependencies to a constructor in the context of the given instance.
* @param {Function} Constructor The constructor function to use.
* @param {!Object} instance The instance to use.
*/
Injector.prototype.inject = function (Constructor, instance) {
var keys = Constructor.prototype.$deps || [];
var deps = keys.map(this.getService, this);
Constructor.apply(instance, deps);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment