2

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....

Kal800
  • 31
  • 6
  • Take a look at this link https://github.com/Rikj000/Saunter-MQTTnet-AspNet5-AttributeRouting-ExampleProject it might help you – Hussein Beygi May 25 '22 at 17:39

1 Answers1

1

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);
Kal800
  • 31
  • 6