# ClientsContainer

**Kind:** Class

**Source:** [`packages/microservices/container.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/container.ts#L3)

**Part of:** [Microservices](subsystem-packages-microservices)

`ClientsContainer` manages a collection of `ClientProxy` instances used by the microservices layer. It provides a central place to register clients, retrieve all registered clients, and clear the collection during cleanup or lifecycle transitions.

## Methods

| Method | Signature | Returns |
|---|---|---|
| `getAllClients` | `getAllClients()` | `ClientProxy[]` |
| `addClient` | `addClient(client: ClientProxy)` | `void` |
| `clear` | `clear()` | `void` |

## Diagram

```mermaid
graph LR
  A[ClientProxy] -->|addClient()| B[ClientsContainer]
  B -->|getAllClients()| C[ClientProxy[]]
  B -->|clear()| D[Empty client collection]
```

## Usage

```ts
import {
  ClientProxyFactory,
  ClientsContainer,
  Transport,
} from '@nestjs/microservices';

const clientsContainer = new ClientsContainer();

const ordersClient = ClientProxyFactory.create({
  transport: Transport.TCP,
  options: {
    host: 'localhost',
    port: 3001,
  },
});

clientsContainer.addClient(ordersClient);

const clients = clientsContainer.getAllClients();

for (const client of clients) {
  await client.connect();
}

// Remove registered client references during cleanup.
clientsContainer.clear();
```

## AI Coding Instructions

- Register each `ClientProxy` with `addClient()` before expecting it to be available through `getAllClients()`.
- Treat `getAllClients()` as the source of registered clients when implementing bulk connection, shutdown, or health-check behavior.
- Ensure client lifecycle cleanup is handled explicitly; clearing the container removes registrations but may not close active client connections.
- Avoid creating duplicate client registrations for the same logical service without first considering the intended replacement or cleanup behavior.
- Keep `ClientsContainer` focused on client registration and lookup rather than transport-specific messaging logic.
