container.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.getFromContainer = exports.useContainer = void 0;
  4. /**
  5. * Container to be used by this library for inversion control. If container was not implicitly set then by default
  6. * container simply creates a new instance of the given class.
  7. */
  8. const defaultContainer = new (class {
  9. constructor() {
  10. this.instances = [];
  11. }
  12. get(someClass) {
  13. let instance = this.instances.find(instance => instance.type === someClass);
  14. if (!instance) {
  15. instance = { type: someClass, object: new someClass() };
  16. this.instances.push(instance);
  17. }
  18. return instance.object;
  19. }
  20. })();
  21. let userContainer;
  22. let userContainerOptions;
  23. /**
  24. * Sets container to be used by this library.
  25. */
  26. function useContainer(iocContainer, options) {
  27. userContainer = iocContainer;
  28. userContainerOptions = options;
  29. }
  30. exports.useContainer = useContainer;
  31. /**
  32. * Gets the IOC container used by this library.
  33. */
  34. function getFromContainer(someClass) {
  35. if (userContainer) {
  36. try {
  37. const instance = userContainer.get(someClass);
  38. if (instance)
  39. return instance;
  40. if (!userContainerOptions || !userContainerOptions.fallback)
  41. return instance;
  42. }
  43. catch (error) {
  44. if (!userContainerOptions || !userContainerOptions.fallbackOnErrors)
  45. throw error;
  46. }
  47. }
  48. return defaultContainer.get(someClass);
  49. }
  50. exports.getFromContainer = getFromContainer;
  51. //# sourceMappingURL=container.js.map