DEV Community

Discussion on: NodeJs Singleton Injector

Collapse
 
anduser96 profile image
Andrei Gatej

Interesting!

You can also get a singleton just by exporting a new instance of a class from a file.

Say you want to have a singleton of a DB class, in your db/index.js you would have the following:

class Database {
  static connection;
  /* ... */
 }

export default new Database(dbConfig);

And now you could import this in multiple files and you will get the same instance.

This is possible due to how modules are designed to work in node. Long story short, the modules are cached.

Collapse
 
elasticrash profile image
Stefanos Kouroupis

Yes I've seen it been done like that before. But I always found it a bit awkward (syntactically). I ll be the first to admit that this idea in some respects it's equally awkward...but why not.

I choose to do it like that because we usually have lots of things to manage in a single service.

A typical service will have the following

Rabbitmq
Database
Vault
Elasticsearch