diff --git a/Source/MQTTnet.AspnetCore/MqttHostedServer.cs b/Source/MQTTnet.AspnetCore/MqttHostedServer.cs index 4c74f6a43..3dfd6c648 100644 --- a/Source/MQTTnet.AspnetCore/MqttHostedServer.cs +++ b/Source/MQTTnet.AspnetCore/MqttHostedServer.cs @@ -12,37 +12,26 @@ namespace MQTTnet.AspNetCore; -public sealed class MqttHostedServer : MqttServer, IHostedService +public sealed class MqttHostedServer : BackgroundService { - readonly IHostApplicationLifetime _hostApplicationLifetime; readonly MqttServerFactory _mqttFactory; - public MqttHostedServer( - IHostApplicationLifetime hostApplicationLifetime, MqttServerFactory mqttFactory, MqttServerOptions options, IEnumerable adapters, - IMqttNetLogger logger) : base(options, adapters, logger) + IMqttNetLogger logger + ) { + MqttServer = new(options, adapters, logger); _mqttFactory = mqttFactory ?? throw new ArgumentNullException(nameof(mqttFactory)); - _hostApplicationLifetime = hostApplicationLifetime; - } - - public async Task StartAsync(CancellationToken cancellationToken) - { - // The yield makes sure that the hosted service is considered up and running. - await Task.Yield(); - - _hostApplicationLifetime.ApplicationStarted.Register(OnStarted); - } - - public Task StopAsync(CancellationToken cancellationToken) - { - return StopAsync(_mqttFactory.CreateMqttServerStopOptionsBuilder().Build()); } - void OnStarted() + public MqttServer MqttServer { get; } + protected override Task ExecuteAsync(CancellationToken stoppingToken) + => MqttServer.StartAsync(); + public override async Task StopAsync(CancellationToken cancellationToken) { - _ = StartAsync(); + await MqttServer.StopAsync(_mqttFactory.CreateMqttServerStopOptionsBuilder().Build()); + await base.StopAsync(cancellationToken); } -} \ No newline at end of file +} diff --git a/Source/MQTTnet.AspnetCore/ServiceCollectionExtensions.cs b/Source/MQTTnet.AspnetCore/ServiceCollectionExtensions.cs index 915f6791c..2f03d0334 100644 --- a/Source/MQTTnet.AspnetCore/ServiceCollectionExtensions.cs +++ b/Source/MQTTnet.AspnetCore/ServiceCollectionExtensions.cs @@ -45,8 +45,8 @@ public static void AddHostedMqttServer(this IServiceCollection services) services.TryAddSingleton(new MqttServerFactory()); services.AddSingleton(); - services.AddSingleton(s => s.GetService()); - services.AddSingleton(s => s.GetService()); + services.AddHostedService(s => s.GetService()); + services.AddSingleton(s => s.GetService().MqttServer); } public static IServiceCollection AddHostedMqttServerWithServices(this IServiceCollection services, Action configure)