fix LoadingRetainedMessageAsync not exec (#2025)

because IHostedService StartAsync before startup Configure
see https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-8.0#ihostapplicationlifetime
This commit is contained in:
pigwing
2024-06-22 15:24:25 +02:00
committed by GitHub
parent b95d352236
commit e18a91a4b5
+28 -3
View File
@@ -16,26 +16,51 @@ namespace MQTTnet.AspNetCore
public sealed class MqttHostedServer : MqttServer, IHostedService public sealed class MqttHostedServer : MqttServer, IHostedService
{ {
readonly MqttFactory _mqttFactory; readonly MqttFactory _mqttFactory;
#if NETCOREAPP3_1_OR_GREATER
public MqttHostedServer(MqttFactory mqttFactory, MqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger) : base( readonly IHostApplicationLifetime _hostApplicationLifetime;
public MqttHostedServer(IHostApplicationLifetime hostApplicationLifetime, MqttFactory mqttFactory,
MqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger) : base(
options,
adapters,
logger)
{
_mqttFactory = mqttFactory ?? throw new ArgumentNullException(nameof(mqttFactory));
_hostApplicationLifetime = hostApplicationLifetime;
}
#else
public MqttHostedServer(MqttFactory mqttFactory,
MqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger) : base(
options, options,
adapters, adapters,
logger) logger)
{ {
_mqttFactory = mqttFactory ?? throw new ArgumentNullException(nameof(mqttFactory)); _mqttFactory = mqttFactory ?? throw new ArgumentNullException(nameof(mqttFactory));
} }
#endif
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken)
{ {
// The yield makes sure that the hosted service is considered up and running. // The yield makes sure that the hosted service is considered up and running.
await Task.Yield(); await Task.Yield();
#if NETCOREAPP3_1_OR_GREATER
_hostApplicationLifetime.ApplicationStarted.Register(OnStarted);
#else
_ = StartAsync(); _ = StartAsync();
#endif
} }
public Task StopAsync(CancellationToken cancellationToken) public Task StopAsync(CancellationToken cancellationToken)
{ {
return StopAsync(_mqttFactory.CreateMqttServerStopOptionsBuilder().Build()); return StopAsync(_mqttFactory.CreateMqttServerStopOptionsBuilder().Build());
} }
#if NETCOREAPP3_1_OR_GREATER
private void OnStarted()
{
_ = StartAsync();
}
#endif
} }
} }