您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Injector.ts 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import 'reflect-metadata';
  2. import { Type } from './Util';
  3. import { FrontworkComponent } from '../Types/FrontworkComponent';
  4. /**
  5. * The Injector stores services and resolves requested instances.
  6. */
  7. export const Injector = new class {
  8. injectionQueue :any[] = []
  9. rootInterface : Type<any>
  10. root : Type<any>
  11. rootModules : Type<any>[] = []
  12. moduleObjs : {[key in string] : FrontworkComponent} = {}
  13. /**
  14. * Resolves instances by injecting required services
  15. * @param {Type<any>} target
  16. * @returns {T}
  17. */
  18. resolve<T>(target: Type<any>): T {
  19. // tokens are required dependencies, while injections are resolved tokens from the Injector
  20. if(this.moduleObjs[target.name])
  21. return this.moduleObjs[target.name] as any
  22. if(target.name === this.rootInterface.name || target.name === this.root.name){
  23. let modules = this.rootModules.map(m => {
  24. const module = new m()
  25. this.moduleObjs[m.name] = module
  26. return module
  27. })
  28. const rootobj = new this.root(modules);
  29. this.moduleObjs[this.rootInterface.name] = rootobj
  30. this.moduleObjs[target.name] = rootobj
  31. while(this.injectionQueue.length > 0){
  32. const i = this.injectionQueue.shift()
  33. if(this.moduleObjs[i.what.name])
  34. i.target[i.where] = this.moduleObjs[i.what.name]
  35. else
  36. this.injectionQueue.push()
  37. }
  38. this.injectionQueue.forEach(i => {
  39. i.target[i.where] = this.moduleObjs[i.what.name]
  40. })
  41. return rootobj
  42. }
  43. this.moduleObjs[target.name] = new target()
  44. return this.moduleObjs[target.name] as any
  45. }
  46. };