1
/**
2
 * Container options.
3
 */
4
export interface UseContainerOptions {
5

6
    /**
7
     * If set to true, then default container will be used in the case if given container haven't returned anything.
8
     */
9
    fallback?: boolean;
10

11
    /**
12
     * If set to true, then default container will be used in the case if given container thrown an exception.
13
     */
14
    fallbackOnErrors?: boolean;
15

16
}
17

18
export type ContainedType<T> = { new (...args: any[]): T } | Function;
19

20
export interface ContainerInterface {
21
    get<T>(someClass: ContainedType<T>): T;
22
}
23

24
/**
25
 * Container to be used by this library for inversion control. If container was not implicitly set then by default
26
 * container simply creates a new instance of the given class.
27
 */
28 5
const defaultContainer: ContainerInterface = new (class implements ContainerInterface {
29 5
    private instances: { type: Function, object: any }[] = [];
30

31 5
    get<T>(someClass: ContainedType<T>): T {
32 5
        let instance = this.instances.find(i => i.type === someClass);
33 5
        if (!instance) {
34 5
            instance = { type: someClass, object: new (someClass as new() => T)()};
35 5
            this.instances.push(instance);
36
        }
37

38 5
        return instance.object;
39
    }
40 5
})();
41

42
let userContainer: ContainerInterface;
43
let userContainerOptions: UseContainerOptions|undefined;
44

45
/**
46
 * Sets container to be used by this library.
47
 */
48 5
export function useContainer(iocContainer: ContainerInterface, options?: UseContainerOptions) {
49 0
    userContainer = iocContainer;
50 0
    userContainerOptions = options;
51
}
52

53
/**
54
 * Gets the IOC container used by this library.
55
 */
56 5
export function getFromContainer<T>(someClass: ContainedType<T>): T {
57 5
    if (userContainer) {
58 0
        try {
59 0
            const instance = userContainer.get(someClass);
60 0
            if (instance)
61 0
                return instance;
62

63 0
            if (!userContainerOptions || !userContainerOptions.fallback)
64 0
                return instance;
65

66
        } catch (error) {
67 0
            if (!userContainerOptions || !userContainerOptions.fallbackOnErrors)
68 0
                throw error;
69
        }
70
    }
71 5
    return defaultContainer.get<T>(someClass);
72
}

Read our documentation on viewing source code .

Loading