container.js 1.4 KB

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