-
-
Save alejofernandez/5693758 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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