> For the complete documentation index, see [llms.txt](https://docs.nestjstools.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nestjstools.com/components/message-bus.md).

# Message Bus

## 📬 MessageBus

The `MessageBus` It is the **core interface** used to **dispatch messages** within your microservice architecture. It acts as the gateway between your application and the configured messaging channels, enabling seamless communication between services.

Whether you're calling from a controller, service, or any provider, the `MessageBus` gives you a powerful and type-safe way to route and send messages through your event-driven system.

***

### 🚀 What Is the MessageBus?

The `MessageBus` is injected via the `@MessageBus('bus.name')` decorator and gives you access to methods that allow you to:

* Send messages to specific handlers via routing
* Send raw or structured messages
* Target a specific **channel** (e.g., in-memory, AMQP)
* Trigger synchronous or asynchronous processing

***

### 🛠 Injecting the MessageBus

When configuring your messaging module, you define named buses. To use a bus, inject it using its name.

#### Example

```ts
import { Controller, Get } from '@nestjs/common';
import { MessageBus, IMessageBus, RoutingMessage } from '@nestjstools/messaging';
import { SendMessage } from './messages/send-message';

@Controller()
export class AppController {
  constructor(@MessageBus('message.bus') private readonly messageBus: IMessageBus) {}

  @Get()
  async dispatch(): Promise<string> {
    await this.messageBus.dispatch(
      new RoutingMessage(new SendMessage('Hello World!'), 'your.message'),
    );
    return 'Message dispatched!';
  }
}
```

***

### 🧩 RoutingMessage Structure

To route a message to the correct handler, use the `RoutingMessage` class:

```ts
new RoutingMessage(payload: object, route: string, messageOptions?: MessageOptions)
```

#### Example:

```ts
new RoutingMessage(
  new SendMessage('User created'),
  'user.created',
);
```

***

### 💡 Bus-to-Channel Mapping

In your configuration, each bus can be connected to multiple channels:

```ts
MessagingModule.forRoot({
  buses: [
    {
      name: 'message.bus',
      channels: ['my-channel'], // All messages from this bus go here
    },
  ],
  channels: [
    new InMemoryChannelConfig({
      name: 'my-channel',
    }),
  ],
})
```

> ✅ A message dispatched from a bus is passed to each of its configured channels.

***

### 🔄 One Bus, Many Channels

Each bus can dispatch to **multiple channels**, and you can even configure different channels (e.g., RabbitMQ + InMemory) to receive the same message for hybrid systems.

***

### 🔐 Benefits of MessageBus

| Feature      | Benefit                                                               |
| ------------ | --------------------------------------------------------------------- |
| ✅ Type-safe  | Dispatch class-based messages with strict typing                      |
| 🔌 Pluggable | Supports multiple channels per bus                                    |
| 📡 Scalable  | Easily add more channels or handlers without changing your core logic |
| 🧪 Testable  | Easily mock or simulate dispatches in testing environments            |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nestjstools.com/components/message-bus.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
