Skip to content

Commit

Permalink
Improving container types, introducing ContainerInterface and Contain…
Browse files Browse the repository at this point in the history
…edType.
  • Loading branch information
saboya committed Apr 23, 2018
1 parent 6c0ad13 commit b0229d9
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,39 +15,45 @@ export interface UseContainerOptions {

}

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

export interface ContainerInterface {
get<T>(someClass: ContainedType<T>): T;
}

/**
* Container to be used by this library for inversion control. If container was not implicitly set then by default
* container simply creates a new instance of the given class.
*/
export const defaultContainer: { get<T>(someClass: { new (...args: any[]): T }|Function): T } = new (class {
const defaultContainer: ContainerInterface = new (class implements ContainerInterface {
private instances: { type: Function, object: any }[] = [];

get<T>(someClass: { new (...args: any[]): T }): T {
let instance = this.instances.find(instance => instance.type === someClass);
get<T>(someClass: ContainedType<T>): T {
let instance = this.instances.find(i => i.type === someClass);
if (!instance) {
instance = { type: someClass, object: new someClass() };
instance = { type: someClass, object: new (someClass as new() => T)()};
this.instances.push(instance);
}

return instance.object;
}
})();

let userContainer: { get<T>(someClass: { new (...args: any[]): T }|Function): T };
let userContainer: ContainerInterface;
let userContainerOptions: UseContainerOptions|undefined;

/**
* Sets container to be used by this library.
*/
export function useContainer(iocContainer: { get(someClass: any): any }, options?: UseContainerOptions) {
export function useContainer(iocContainer: ContainerInterface, options?: UseContainerOptions) {
userContainer = iocContainer;
userContainerOptions = options;
}

/**
* Gets the IOC container used by this library.
*/
export function getFromContainer<T>(someClass: { new (...args: any[]): T }|Function): T {
export function getFromContainer<T>(someClass: ContainedType<T>): T {
if (userContainer) {
try {
const instance = userContainer.get(someClass);
Expand Down

0 comments on commit b0229d9

Please sign in to comment.