Search code examples
.netasp.net-web-apimqttnet

MQTTnet - creating service for .net 6 Minimal Api


Could anybody provide example code to create injectable MQTTnet service to be used by API Controller in .net 6.0? I've done something like this:

MqttClientOptionsBuilder mqbuilder = new MqttClientOptionsBuilder()
        .WithClientId("VTSCMgmntC")
        .WithTcpServer("192.168.1.75", 1883);

ManagedMqttClientOptions mqoptions = new ManagedMqttClientOptionsBuilder()
       .WithAutoReconnectDelay(TimeSpan.FromSeconds(60))
       .WithClientOptions(mqbuilder.Build())
       .Build();

builder.Services.AddSingleton<IManagedMqttClient>(new MqttFactory().CreateManagedMqttClient());

and on the controller side, I've got:

 private readonly VTSCMContext _context;
 private readonly IManagedMqttClient _mqttclient;

    public VTSCMgmtController(VTSCMContext context, IManagedMqttClient mqttclient)
    {
        _context = context;
        _mqttclient = mqttclient;
    }

    [HttpGet]
    public void pubtest()
    {
        _mqttclient.PublishAsync("test");
    }

Obviously nothing gets published at all....


Solution

  • Adding the code that worked for future reference:

    IMqttClientOptions options = new MqttClientOptionsBuilder()
            .WithClientId("")
            .WithTcpServer("", 1883)
            .WithCredentials("", "")
            .Build();
    
    IMqttClient mqttclient = new MqttFactory().CreateMqttClient();
    
    var connection =  mqttclient.ConnectAsync(options, CancellationToken.None);
    
    connection.Wait();
    var res = connection.Result;
    
    builder.Services.AddSingleton<IMqttClient>(mqttclient);