You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.6 KiB
59 lines
1.6 KiB
class Container {
|
|
constructor(definitions = {}) {
|
|
this.definitions = definitions
|
|
this.instances = {}
|
|
this.statics = {}
|
|
this.di = false
|
|
}
|
|
|
|
has(service) {
|
|
return !!this.definitions[service]
|
|
}
|
|
|
|
service(service = false) {
|
|
if ( service === false ) {
|
|
return new Proxy({}, {
|
|
get: (obj, prop) => {
|
|
return this.service(prop)
|
|
}
|
|
})
|
|
}
|
|
|
|
if ( !this.definitions[service] ) {
|
|
throw new Error('No such service registered with this container.')
|
|
}
|
|
|
|
// Store the static reference first.
|
|
// This allows us to resolve circular dependencies.
|
|
if ( !this.statics[service] ) {
|
|
this.statics[service] = this.definitions[service]
|
|
this.di.make(this.statics[service])
|
|
}
|
|
|
|
if ( !this.instances[service] ) {
|
|
const ServiceClass = this.statics[service]
|
|
this.instances[service] = new ServiceClass()
|
|
}
|
|
|
|
return this.instances[service]
|
|
}
|
|
|
|
register(service_name, service_class) {
|
|
this.definitions[service_name] = service_class
|
|
}
|
|
|
|
register_as_instance(service_name, service_instance) {
|
|
this.instances[service_name] = service_instance
|
|
}
|
|
|
|
__is_injectable(Class) {
|
|
console.log('WARNING: use of flitter-di/Container#__is_injectable is deprecated and will be removed in the future')
|
|
return (
|
|
Class.services
|
|
&& Array.isArray(Class.services)
|
|
)
|
|
}
|
|
}
|
|
|
|
module.exports = exports = Container
|