dotnet / dotnet/MQTTnet

Use of LoadingRetainedMessagesEvent with AspNetCore DI Framework

Open
#1,898 0 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
C#
Stars
5.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

### Describe your question
I am attempting to start the server according to the [Server ASP Net example](https://github.com/dotnet/MQTTnet/blob/master/Samples/Server/Server_ASP_NET_Samples.cs).
I have added EventHandlers to the `LoadingRetainedMessageAsync`, `RetainedMessageChangedAsync` and `RetainedMessagesClearedAsync` events (see code example below).

Saving and deleting retained messages works, but the server does not load the retained messages on startup.
As far as I can tell this is because by the time the EventHandler for `LoadingRetainedMessageAsync` is registered by the `app.UseMqttServer()` method the server is already started and the event has already been invoked.

What is the correct way to register the EventHandler for `LoadingRetainedMessageAsync` in this setup?

### Which project is your question related to?

- Server

### Code example
```c#
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MQTTnet.AspNetCore;
using MQTTnet.Server;
using System.Text.Json;

namespace MQTTnet.Server.Example
{
public class Program
{
public static Task Main()
{
var host = Host.CreateDefaultBuilder(Array.Empty())
.ConfigureWebHostDefaults(
webBuilder =>
{
webBuilder.UseKestrel(
o =>
{
o.ListenAnyIP(1883, l => l.UseMqtt());
o.ListenAnyIP(5000);
});
webBuilder.UseStartup();
});
return host.RunConsoleAsync();
}

sealed class MqttController
{
private readonly string path = Path.Combine(Path.GetTempPath(), "retainedMessages.json");

public Task LoadRetainedMessages(LoadingRetainedMessagesEventArgs args)
{
if (File.Exists(path))
{
args.LoadedRetainedMessages = JsonSerializer.Deserialize>(File.ReadAllText(path));
}
return Task.CompletedTask;
}

public Task ChangeRetainedMessage(RetainedMessageChangedEventArgs args)
{
File.WriteAllText(path, JsonSerializer.Serialize(args.StoredRetainedMessages));
return Task.CompletedTask;
}

public Task ClearRetainedMessages(EventArgs args)
{
File.WriteAllText(path, string.Empty);
return Task.CompletedTask;
}
}

sealed class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment environment, MqttController mqttController)
{
app.UseRouting();

app.UseEndpoints(
endpoints =>
{
endpoints.MapConnectionHandler(
"/mqtt",
httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
protocolList => protocolList.FirstOrDefault() ?? string.Empty);
});

app.UseMqttServer(
server =>
{
server.LoadingRetainedMessageAsync += mqttController.LoadRetainedMessages;
server.RetainedMessageChangedAsync += mqttController.ChangeRetainedMessage;
server.RetainedMessagesClearedAsync += mqttController.ClearRetainedMessages;
});
}

public void ConfigureServices(IServiceCollection services)
{
services.AddHostedMqttServer(
optionsBuilder =>
{
optionsBuilder.WithDefaultEndpoint();
});

services.AddMqttConnectionHandler();
services.AddConnections();

services.AddSingleton();
}
}
}
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.