dimanche 2 août 2020

How to make availabe a singleton instace to all over the service?

This is how I'm implementing a singleton class

import { AClient } from 'libbrary'
import { Container, Service } from 'typedi';

@Service()
class MyClass {
    private client: AClient;
    
    static getInstance(): MyClass {
        return Container.get(MyClass);
    }
    
    getClient(): AClient {
        if(this.client !== null){
            return this.client;
        }
        this.client = new AClient();
        return this.client;
    }
}

Here the main focus is using Acliet().
And I'm implementing methods of this client in the following way.

class AClientMethodsImplementation {
    async getSomeData() {
        // I need client here so that I can use client.get()
    }
}

Now I should use these methods in my service.

class NeedDataHere {
    // Not only here, in the entire project I need this many places.
    // should I create AClientMethodsImplementation() instance everytime?
    // If that is the case what is the point of a singleton?
    // How to achieve this? What is the correct approach?
}

Am I following the correct approach? Or what is the best way to handle this scenario? I'm saying this is a problem because I observed that hitting getSomeData() by creating new AClientMethodsImplementation class every time is giving the same result even I change input data to that function. I doubt it's caching somewhere.

Aucun commentaire:

Enregistrer un commentaire