MQTTnet - 为 .net 6 Minimal 创建服务 Api

MQTTnet - creating service for .net 6 Minimal Api

任何人都可以提供示例代码来创建可注入的 MQTTnet 服务以供 API 控制器在 .net 6.0 中使用吗?我做过这样的事情:

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());

在控制器端,我有:

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

显然什么都没有发布....

添加有效的代码以供将来参考:

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