Moonglade

Modern Markdown blogging with AI-powered localization and search.

Tag: C#


Creating an MQTT client with automatic reconnection using `ManagedMqttClient` from MQTTnet

This article introduces how to simplify MQTT communication development in C# projects by leveraging the ManagedMqttClient extension package from MQTTnet. Compared to the native MqttClient, this extension package has built-in features for automatic reconnection, offline message queuing, and automatic subscription state recovery, significantly reducing the maintenance cost of reconnection logic. The article focuses on analyzing three core concepts in the MQTT protocol: QoS (Quality of Service) levels, where QoS 1 (at least once) is suitable for most scenarios, QoS 2 (exactly once) is reliable but has high performance overhead, and QoS 0 is used for low-priority data where packet loss is acceptable; the CleanSession flag, where setting it to false allows the Broker to cache QoS 1/2 messages while the client is offline and resend them after reconnection, which is ideal for devices requiring data integrity; and the Retain message mechanism, which allows the Broker to store the latest state of a Topic so that new subscribers can immediately obtain the most recent data, commonly used for device state synchronization. Finally, through examples of a temperature sensor and an alarm system, the article demonstrates how to combine these parameters based on business requirements to balance message reliability, real-time performance, and system resource consumption, providing clear guidelines for MQTT configuration in real-world projects.

Views 334
.NET C# IoT MQTT MQTTnet ManagedMqttClient

Building an IoC Container from Scratch with .NET Framework 4.7.2

This article dissects the core mechanisms of dependency injection by manually implementing a minimalist IoC container. The author points out that IoC primarily consists of three elements: registration, resolution, and lifecycle management. The article presents implementation code based on C# reflection and dictionary mapping, with a focus on analyzing how the Resolve method recursively searches for constructor parameters and automatically creates dependency instances, thereby solving the cumbersome problem of manually assembling objects. Through a test case involving a three-level dependency chain, the article verifies that the container can automatically populate constructor parameters and correctly implements the singleton pattern, ensuring that the same service instance is returned during multiple resolutions. The author also notes that although this simplified container lacks enterprise-grade features such as Scoped lifecycle, thread-safe locking, circular dependency detection, and IDisposable resource management, its 50-plus lines of code precisely reveal the essence of an IoC container: achieving inversion of control by recursively resolving the dependency tree and building objects layer by layer from the leaf nodes upward.

Views 238
.NET C# DI Container Dependency Injection Inversion of Control IoC

StackExchange.Redis Disconnection Pitfalls

This article summarizes common pitfalls and solutions for StackExchange.Redis connection interruptions and reconnection failures. The primary issue is that the default configuration has `abortConnect` set to `true`, which prevents automatic recovery after a disconnection. To enable automatic reconnection, you must set `abortConnect=false` in the connection string. Second, reconnection failures may still occur under high load. It is recommended to catch `RedisConnectionException` and manually rebuild the `ConnectionMultiplexer` instance. Regarding the issue in Linux environments where reconnection can take up to 15 minutes after a disconnection, the root cause is that the kernel parameter `tcp_retries2` has a default value that is too large. You can adjust it to `5` using the `sysctl` command to accelerate TCP layer release. Finally, it is emphasized that `ConnectionMultiplexer` must be used as a singleton. Creating a new connection for every request is strictly prohibited, as it can lead to a connection explosion. It is recommended to register it as a singleton service in dependency injection.

Views 180
.NET BestPractices C# Redis StackExchange.Redis Troubleshooting