Fluent API initialization
Now that you manage the complete lifecycle of SyMqtt, you can optimize your bootstrap code using the fluent builder API.
To maximize readability and reduce boilerplate setup operations, SyMqtt supports an expressive Fluent API configuration pattern. Because methods like AddChannel, AddTopic, and Initialize return the modified instance of SyMqttBox (return this;), you can chain the entire application bootstrap pipeline into a single, clean declaration block.
The unified bootstrap flow
Section titled “The unified bootstrap flow”By chaining your topology components, you can declare channels, attach detached standalone topic receivers with inline asynchronous handlers, feed client parameters, and fire up the connection seamlessly.
Here is a full enterprise-grade example of a chained Fluent initialization:
using SyMqtt;using SyMqtt.Tools;using System;using System.Threading.Tasks;
// 1. Initialize the box framework with fundamental settingsvar mqttBox = new SyMqttBox{ TopicsPrefix = "smartcontrol", AutoReconnect = true, Logger = new SyMqttConsoleLogger()};
try{ // 2. Build the entire layout topology using fluent method chaining var connectionResult = await mqttBox // Inline channel creation using the simplified string-based constructor .AddChannel(new SyMqttChannel(mqttBox, "channel_01", "boxmessage", "boardmessage"))
// Inline standalone receiver registration with its delegate handler .AddTopic(new SyMqttReceiverTopicHolder("topic02", "ccc/#").AddReceivedMessageHandler( (inPayload, messageInfo) => { mqttBox.Logger?.WriteLine( $"(2) Broadcast intercepted: {inPayload} on topic '{messageInfo.PublishTopic}'", ConsoleColor.Blue ); return Task.CompletedTask; }))
// Inline client parameters and secure TLS setup .Initialize(new SyMqttClientParameters { CleanSession = true, ClientId = "SyMqtt_console_test", TcpServer = "mybroker.net", TcpPort = 8883, User = "", Password = "", TlsOptions = new SyMqttTlsOptions { UseTls = true, AllowUntrustedCertificates = false } })
// Finalize the chain by opening the transport connection natively .OpenConnectionAsync();
// 3. Evaluate the unified bootstrap result if (connectionResult.Success) { Console.WriteLine("SyMqtt system is fluently configured and online!"); } else { Console.WriteLine($"Fluency Bootstrap connected but reported an engine issue: {connectionResult.ErrorDescription}"); }}catch (Exception ex){ Console.WriteLine($"Fluency Bootstrap crashed during execution: {ex.Message}");}Method chaining order constraints
Section titled “Method chaining order constraints”While Fluent APIs offer incredible structural flexibility, the underlying architecture of SyMqtt requires a strict operational sequence during execution. When designing your chained expressions, ensure you always follow this semantic order:
- Topology definition first: Add all your layout structures (
AddChannel,AddTopic) at the absolute beginning of the chain. - Engine initialization second: Call
.Initialize(...)to construct the underlying MQTTnet infrastructure, attach internal state handlers, and lock down your profile. - Execution last: Always place
.OpenConnectionAsync()at the very tail of the expression.
Operational benefits of fluent API initialization
Section titled “Operational benefits of fluent API initialization”- High Scannability: The complete communication topology of your microservice or daemon process is visible at a single glance within a single logical scope.
- State Protection: Since SyMqtt prevents adding channels or topics after the connection to the broker was opened, chaining
.Initialize(...).OpenConnectionAsync()strictly at the tail of the layout definition guarantees that configuration errors are caught early during the application startup sequence, ensuring a deterministic initialization state.