Path: redb-route/redb.Route.MqttNet/Extensions/ServiceCollectionExtensions.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.MqttNet/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; using redb.Route.MqttNet.Connection; namespace redb.Route.MqttNet; /// /// DI registration for the MQTT connector. /// public static class ServiceCollectionExtensions { /// /// Registers the MQTT component with the route framework. /// /// /// services.AddRedbRoute(); /// services.AddRedbRouteMqtt(mqtt => /// { /// mqtt.AddBroker("main", o => /// { /// o.Server = "localhost"; /// o.Port = 1883; /// }); /// }); /// /// /// public static IServiceCollection AddRedbRouteMqtt( this IServiceCollection services, Action? configure = null) { var builder = new MqttConfigurationBuilder(services); configure?.Invoke(builder); services.AddSingleton(builder.BuildRegistry()); services.AddSingleton(builder.BuildClientFactory()); services.AddSingleton(); // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteContextConfigurator((sp, context) => { var component = sp.GetRequiredService(); component.BrokerRegistry = sp.GetRequiredService(); component.ClientFactory = sp.GetRequiredService(); context.AddComponent(component); }); return services; } } /// /// Fluent builder for MQTT DI configuration. /// public sealed class MqttConfigurationBuilder { private readonly IServiceCollection _services; private readonly MqttBrokerRegistry _brokerRegistry = new(); private IMqttClientFactory? _clientFactory; internal MqttConfigurationBuilder(IServiceCollection services) => _services = services; /// The service collection. public IServiceCollection Services => _services; /// /// Registers a named broker for use with Mqtt.Subscribe("topic").Broker("name"). /// public MqttConfigurationBuilder AddBroker(string name, Action configure) { var options = new MqttBrokerOptions(); configure(options); _brokerRegistry.Register(name, options); return this; } /// /// Registers a named broker with pre-built options. /// public MqttConfigurationBuilder AddBroker(string name, MqttBrokerOptions options) { _brokerRegistry.Register(name, options); return this; } /// /// Replaces the default client factory (for testing or custom client management). /// public MqttConfigurationBuilder UseClientFactory(IMqttClientFactory factory) { _clientFactory = factory; return this; } internal IMqttBrokerRegistry BuildRegistry() => _brokerRegistry; internal IMqttClientFactory BuildClientFactory() => _clientFactory ?? new DefaultMqttClientFactory(); }