You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

86 lines
2.9 KiB

  1. using System;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Microsoft.Extensions.Hosting;
  4. using MQTTnet.Adapter;
  5. using MQTTnet.Diagnostics;
  6. using MQTTnet.Server;
  7. using MQTTnet.Implementations;
  8. namespace MQTTnet.AspNetCore
  9. {
  10. public static class ServiceCollectionExtensions
  11. {
  12. public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, IMqttServerOptions options)
  13. {
  14. if (options == null) throw new ArgumentNullException(nameof(options));
  15. services.AddSingleton(options);
  16. services.AddHostedMqttServer();
  17. return services;
  18. }
  19. public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, Action<MqttServerOptionsBuilder> configure)
  20. {
  21. var builder = new MqttServerOptionsBuilder();
  22. configure(builder);
  23. services.AddSingleton<IMqttServerOptions>(builder.Build());
  24. services.AddHostedMqttServer();
  25. return services;
  26. }
  27. public static IServiceCollection AddHostedMqttServer<TOptions>(this IServiceCollection services)
  28. where TOptions : class, IMqttServerOptions
  29. {
  30. services.AddSingleton<IMqttServerOptions, TOptions>();
  31. services.AddHostedMqttServer();
  32. return services;
  33. }
  34. private static IServiceCollection AddHostedMqttServer(this IServiceCollection services)
  35. {
  36. var logger = new MqttNetLogger();
  37. var childLogger = logger.CreateChildLogger();
  38. services.AddSingleton<IMqttNetLogger>(logger);
  39. services.AddSingleton(childLogger);
  40. services.AddSingleton<MqttHostedServer>();
  41. services.AddSingleton<IHostedService>(s => s.GetService<MqttHostedServer>());
  42. services.AddSingleton<IMqttServer>(s => s.GetService<MqttHostedServer>());
  43. return services;
  44. }
  45. public static IServiceCollection AddMqttWebSocketServerAdapter(this IServiceCollection services)
  46. {
  47. services.AddSingleton<MqttWebSocketServerAdapter>();
  48. services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttWebSocketServerAdapter>());
  49. return services;
  50. }
  51. public static IServiceCollection AddMqttTcpServerAdapter(this IServiceCollection services)
  52. {
  53. services.AddSingleton<MqttTcpServerAdapter>();
  54. services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttTcpServerAdapter>());
  55. return services;
  56. }
  57. public static IServiceCollection AddMqttConnectionHandler(this IServiceCollection services)
  58. {
  59. services.AddSingleton<MqttConnectionHandler>();
  60. services.AddSingleton<IMqttServerAdapter>(s => s.GetService<MqttConnectionHandler>());
  61. return services;
  62. }
  63. }
  64. }