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.
53 lines
2.5 KiB
53 lines
2.5 KiB
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<RabbitMqConnectionOptions>();
|
|
ArgumentNullException.ThrowIfNull(rabbitMqOptions);
|
|
services.AddSingleton<IEventBusSubscriptionManager, InMemoryEventBusSubscriptionManager>();
|
|
services.AddSingleton<IPersistentConnection, RabbitMQPersistentConnection>(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<ILogger<RabbitMQPersistentConnection>>();
|
|
return new RabbitMQPersistentConnection(connectionFactory, logger,
|
|
rabbitMqOptions.TimeoutBeforeReconnecting);
|
|
});
|
|
services.AddSingleton<IEventBus, RabbitMQEventBus>(factory =>
|
|
{
|
|
var persistentConnection = factory.GetService<IPersistentConnection>();
|
|
var subscriptionManager = factory.GetService<IEventBusSubscriptionManager>();
|
|
var logger = factory.GetService<ILogger<RabbitMQEventBus>>();
|
|
|
|
return new RabbitMQEventBus(persistentConnection, subscriptionManager, factory, logger,
|
|
rabbitMqOptions.ExchangeName, rabbitMqOptions.QueueName);
|
|
});
|
|
return services;
|
|
}
|
|
|
|
public static void SubscribeEvent<TEvent, TEvenHandler>(this IServiceProvider services)
|
|
where TEvent : IntegrationEvent where TEvenHandler : IIntegrationEventHandler<TEvent>
|
|
{
|
|
ArgumentNullException.ThrowIfNull(services);
|
|
var eventBus = services.GetRequiredService<IEventBus>();
|
|
eventBus.Subscribe<TEvent, TEvenHandler>();
|
|
}
|
|
} |