Skip to content

Getting Services

Francisco Ruiz edited this page Aug 27, 2024 · 1 revision

Getting services

get(key, options)

The usual way to get a service is using the get(key) method:

const service = container.get('Service');
  • options: { proxyMiddleware: boolean }. See the Container API for more details.

This instantiates the service only the first time, and returns the same instance for each subsequent call. Singleton option is enabled by default in the registration add() method.

getAll(options)

The getAll() method returns an object with all the services registered in the container:

const services = container.getAll();
  • options: { proxyMiddleware: boolean }. See the Container API for more details.

getAll() does not instantiate any of the services. It only returns a callback function for each service that will make the service instance when called.

Then, with this object, we can apply different techniques to get each service:

Destructuring

const { Service1, Service2 } = container.getAll();

const instance1 = Service1(); // Make the instance of the Service1. 
const instance2 = Service2(); // Make the instance of the Service2.

Method chaining

// Instantiate Service1 and Service2.
const instance1 = container.getAll().Service1();
const instance2 = container.getAll().Service2();

Global variable

const services = container.getAll();

const instance1 = services.Service1(); // Instantiate the Service1.
const instance2 = services.Service2(); // Instantiate the Service2.

getFactory(key, options)

If you need a factory for the registered services, you can use the getFactory method, which always returns a different instance of the service:

const instance1 = container.getFactory('Service');
const instance2 = container.getFactory('Service');
// instance1 !== instance2
  • options: { proxyMiddleware: boolean }. See the Container API for more details.

Instead, with get() method, with the default singleton option enabled:

const instance1 = container.get('Service');
const instance2 = container.get('Service');
// instance1 === instance2

1. Getting Started

2. Core Concepts

3. Middleware

4. Caching and Memoization

5. Typescript

6. Considerations

7. API Reference

8. Examples and Use Cases

9. Contributing

We welcome contributions from the community! Whether it's reporting a bug, suggesting a feature, or contributing code, your involvement is key to making Packet.js better. Please check out this section for more details.

10. Support

If you encounter any issues or bugs while using packetjs, or if you have any feature requests, please feel free to open an issue in our GitHub repository. You can report issues, track progress, and engage in discussions with the community via the following link:

11. FAQ

If you have any questions or need further assistance, feel free to reach out via the discussion board.

12. License

Clone this wiki locally