SyMqttBox instantiation, properties and events
Before connecting to your MQTT broker, you need to create an instance of SyMqttBox and configure its basic behavior.
Instantiate the box
Section titled “Instantiate the box”SyMqttBox provides flexibility right from its constructor. You can start completely fresh with an empty box, or you can pre-load it with your existing communication components.
Option 1: Empty instance (Recommended)
Section titled “Option 1: Empty instance (Recommended)”The most common approach is to create an empty box and register your channels and topics later dynamically using fluent methods:
using SyMqtt;
// Create a clean, empty orchestrator instanceusing var mqttBox = new SyMqttBox();Option 2: Bulk injection via constructor
Section titled “Option 2: Bulk injection via constructor”If you already have your channels and topic holders instantiated elsewhere (for example, loaded from a configuration file or dependency injection), you can pass them directly into the constructor:
// Inject predefined channels or topic holders right at birthvar mqttBox = new SyMqttBox(myChannelsList, mySendersList, myReceiversList);Connection lifecycle events
Section titled “Connection lifecycle events”The SyMqttBox exposes a centralized connection state event that allows your application to react programmatically whenever the underlying MQTT client connects or disconnects from the broker. This is useful for updating user interfaces, pausing local execution loops, or triggering safe-stop protocols during network failures.
The connection state changed event
Section titled “The connection state changed event”SyMqtt provides a multicast delegate that passes the connection state as a boolean parameter:
public Func<bool, Task> OnConnectionStateChanged { get; set; }- True: The client has successfully established a connection with the MQTT broker, and the configured topology has been fully initialized.
- False: The client has lost connection to the broker.
SyMqttwill automatically attempt to recover and reconnect in the background, but this event triggers immediately to allow your application to adapt.
Defensive execution safety: Every handler subscribed to this event is isolated and executed independently within its own task frame. If a user-defined handler throws an exception or crashes,
SyMqttintercepts the failure, logs it via the registered logger, and continues executing the remaining handlers in the invocation list. This protects the primary network threads from unhandled application crashes.
Subscription example
Section titled “Subscription example”Always use the += operator to subscribe to the lifecycle event. This ensures you append your behavior safely without overwriting other framework or telemetry subscribers that might be listening to the same instance.
var box = new SyMqttBox();
// Subscribe to the connection state lifecycle safely box.OnConnectionStateChanged += async (isConnected) => { if (isConnected) { // React to an active connection (e.g., enable UI controls) await Task.Run(() => UpdateSystemStatus(isOnline: true)); } else { // React to a network failure (e.g., activate local fail-safe protocols) await Task.Run(() => TriggerEmergencyStop("Network connection lost")); } };Global properties
Section titled “Global properties”Once you have your instance, you can fine-tune its behavior using several public properties. You can modify these settings at any time, but they generally dictate how the box handles data routing, logging, and unexpected disconnections.
| Property | Type | Default | Description |
|---|---|---|---|
TopicsPrefix | string | "" | A global prefix added automatically to all registered topics (e.g., company/factory). |
AutoReconnect | bool | true | When true, the box automatically attempts to reconnect if the broker connection drops. |
IgnoreRetainedMessages | bool | true | If true, old retained messages waiting on the broker are ignored upon connection. |
DefaultDeliveryOptions | SyMqttDeliveryOptions | new() | The default QoS and MQTT v5 settings applied to messages if no specific options are provided during a publish call. |
Logger | ISyMqttLogger | SyMqttConsoleLogger | The interface used to route diagnostic framework events. Defaults to a built-in console logger but accepts custom external adapters. See the SyMqtt logging guide. |
Configuration example
Section titled “Configuration example”Here is a quick look at how you can spin up a box and tweak its main properties to match your environment:
using SyMqtt;
using var mqttBox = new SyMqttBox{ // Automatically route all messages under a specific root topic TopicsPrefix = "production/line1",
// Ensure the system tries to recover from network failure AutoReconnect = true,
// Ignore stale messages cached by the broker IgnoreRetainedMessages = true};Now that you have your orchestrator instance ready and configured, you need to define your messaging landscape.
Let’s move to the next step to see how to register topic holders and channels.