using Infrastructure.EventBus.RabbitMQ; using Infrastructure.EventBus.Subscriptions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Infrastructure.EventBus; public static class ServiceCollectionExtensions { public static IServiceCollection AddRollerRabbitMQEventBus(this IServiceCollection services, IConfiguration configuration) { ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(services); var rabbitMqOptions = configuration.GetSection(RabbitMqConnectionOptions.SectionName) .Get(); ArgumentNullException.ThrowIfNull(rabbitMqOptions); services.AddSingleton(); services.AddSingleton(factory => { var connectionFactory = new ConnectionFactory { HostName = configuration[RabbitMqConnectionOptions.HOST] ?? rabbitMqOptions.HostName, UserName = configuration[RabbitMqConnectionOptions.USER] ?? rabbitMqOptions.Username, Password = configuration[RabbitMqConnectionOptions.PASSWORD] ?? rabbitMqOptions.Password, DispatchConsumersAsync = rabbitMqOptions.DispatchConsumersAsync, }; var logger = factory.GetService>(); return new RabbitMQPersistentConnection(connectionFactory, logger, rabbitMqOptions.TimeoutBeforeReconnecting); }); services.AddSingleton(factory => { var persistentConnection = factory.GetService(); var subscriptionManager = factory.GetService(); var logger = factory.GetService>(); return new RabbitMQEventBus(persistentConnection, subscriptionManager, factory, logger, rabbitMqOptions.ExchangeName, rabbitMqOptions.QueueName); }); return services; } public static void SubscribeEvent(this IServiceProvider services) where TEvent : IntegrationEvent where TEvenHandler : IIntegrationEventHandler { ArgumentNullException.ThrowIfNull(services); var eventBus = services.GetRequiredService(); eventBus.Subscribe(); } }