UNPKG

1.41 kBJavaScriptView Raw
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 */
5const 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})();
18let userContainer;
19let userContainerOptions;
20/**
21 * Sets container to be used by this library.
22 */
23export function useContainer(iocContainer, options) {
24 userContainer = iocContainer;
25 userContainerOptions = options;
26}
27/**
28 * Gets the IOC container used by this library.
29 */
30export 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
\No newline at end of file