Registry

About

A well known object (known by all), useful for locating other objects/services.

circle-info

You can use a Registry to inject dependencies.

Why use this:

  • In Typescript you can inject dependencies by passing the dependent classes as parameters to constructors, but this increases coupling, since any changes at the constructor parameters will break code everywhere you instanciate this Class.

  • Also, using a Registry will significantly reduce the amount of classes passed to constructors.

  • And it will centralize all dependencies in a single Registry class. (Could be a downside)

circle-check

Implementing using Singleton

Registry.ts
export default class Registry {
    private dependencies: {[name: string]: any} = {};
    private static instance: Registry;
    
    private constructor() {}
    
    provide(name: string, dependency: any) {
        this.dependencies[name] = dependency;
    }
    
    inject(name: string) {
        return this.dependencies[name];
    }
    
    static getInstance() {
        if (!Registry.instance) Registry.instance = new Registry();
        return Registry.instance;
    }
}

Use it anywhere on the code to, provide (create) and inject (get) other class instances (dependencies).

Example (without decorators)

This

Will be substituted by

In the main.ts we instanciate and provide to the Registry all the classes we want.

At the Signup.ts for example we will grab the UserDAO instance created in the main.ts. And as you can see, no classes had to be passed to the constructor as parameter.

Example (with decorators) (in typescript)

circle-info

To work with decorators, we need also to lazy load Signup calls to getUserByID with the .

The same example above, will be substituted by:

Last updated