Skip to content

SyMqttBox instantiation, properties and events

Before connecting to your MQTT broker, you need to create an instance of SyMqttBox and configure its basic behavior.

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.

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 instance
using var mqttBox = new SyMqttBox();

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 birth
var mqttBox = new SyMqttBox(myChannelsList, mySendersList, myReceiversList);

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.

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. SyMqtt will 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, SyMqtt intercepts 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.

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"));
}
};

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.

PropertyTypeDefaultDescription
TopicsPrefixstring""A global prefix added automatically to all registered topics (e.g., company/factory).
AutoReconnectbooltrueWhen true, the box automatically attempts to reconnect if the broker connection drops.
IgnoreRetainedMessagesbooltrueIf true, old retained messages waiting on the broker are ignored upon connection.
DefaultDeliveryOptionsSyMqttDeliveryOptionsnew()The default QoS and MQTT v5 settings applied to messages if no specific options are provided during a publish call.
LoggerISyMqttLoggerSyMqttConsoleLoggerThe interface used to route diagnostic framework events. Defaults to a built-in console logger but accepts custom external adapters.
See the SyMqtt logging guide.

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.