Ver código fonte

Add inject_globally method to DI to bootstrap require()

tags/v0.4.0
Garrett Mills 3 meses atrás
pai
commit
c5330ba18f
1 arquivos alterados com 20 adições e 1 exclusões
  1. 20
    1
      src/DependencyInjector.js

+ 20
- 1
src/DependencyInjector.js Ver arquivo

@@ -50,6 +50,24 @@ class DependencyInjector {
return this.container.has(name)
}

/**
* If called, this method will extend the global nodejs require() method to
* check for injectable classes. If a require value is injectable, it will be
* automatically injected with the services from this DI.
*/
inject_globally() {
const Module = require('module')
const original_require = Module.prototype.require
const di = this

di._original_require = original_require

Module.prototype.require = function() {
const value = original_require.apply(this, arguments)
return di.__is_injectable(value) ? di.make(value) : value
}
}

/**
* Verify that a class is injectable. This means that it has a static __inject
* method and that method takes at least one argument. In almost all cases, this
@@ -60,7 +78,8 @@ class DependencyInjector {
*/
__is_injectable(Class) {
return (
typeof Class.__inject === 'function'
typeof Class === 'function'
&& typeof Class.__inject === 'function'
&& Class.__inject.length > 0
)
}

Carregando…
Cancelar
Salvar