mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-15 00:15:15 +08:00
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:
@@ -16,26 +16,51 @@ namespace MQTTnet.AspNetCore
|
||||
public sealed class MqttHostedServer : MqttServer, IHostedService
|
||||
{
|
||||
readonly MqttFactory _mqttFactory;
|
||||
|
||||
public MqttHostedServer(MqttFactory mqttFactory, MqttServerOptions options, IEnumerable<IMqttServerAdapter> adapters, IMqttNetLogger logger) : base(
|
||||
#if NETCOREAPP3_1_OR_GREATER
|
||||
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,
|
||||
adapters,
|
||||
logger)
|
||||
{
|
||||
_mqttFactory = mqttFactory ?? throw new ArgumentNullException(nameof(mqttFactory));
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// The yield makes sure that the hosted service is considered up and running.
|
||||
await Task.Yield();
|
||||
|
||||
#if NETCOREAPP3_1_OR_GREATER
|
||||
_hostApplicationLifetime.ApplicationStarted.Register(OnStarted);
|
||||
#else
|
||||
_ = StartAsync();
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return StopAsync(_mqttFactory.CreateMqttServerStopOptionsBuilder().Build());
|
||||
}
|
||||
|
||||
#if NETCOREAPP3_1_OR_GREATER
|
||||
private void OnStarted()
|
||||
{
|
||||
_ = StartAsync();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user