Skip to content

Instantly share code, notes, and snippets.

@jankuca
Created May 14, 2012 23:05
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save jankuca/2697994 to your computer and use it in GitHub Desktop.
Save jankuca/2697994 to your computer and use it in GitHub Desktop.
Injector.js
/**
* @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);
};
@danielmlipton
Copy link

Thanks for providing this gist. Thought you'd like to know:

$ jshint injector.js
injector.js: line 54, col 25, 'Contructor' is not defined.

(Just a typo.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment